1、介绍
在java中实现定时任务有几种方式:
-
1、自己写代码,解析cron表达式,或者sleep多长时间在执行一次
-
2、使用内置的timer类来实现
-
3、使用ScheduledThreadPoolExecutor(和timer有区别,timer一个任务抛异常,所有任务都不能用了)
-
3、利用开源的quartz,结合spring进行使用
下面重点讲解Timer
2、代码
public class TimerTest { public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new TimerTask() { //public abstract class TimerTask implements Runnable [@Override](https://my.oschina.net/u/1162528) public void run() { //Fixme Do SameThing System.out.println("Task1"); } }, 1000, 1 * 1000); timer.schedule(new TimerTask() { [@Override](https://my.oschina.net/u/1162528) public void run() { //fixme 一个timer可以启动多个定时任务,他里面维护了一个queue //fixme private final TaskQueue queue = new TaskQueue(); //fixme private final TimerThread thread = new TimerThread(queue); //fixme queue.add(task); System.out.println("Task2"); } }, 200, 2 * 1000); } /** * TimerThread 的run方法调用mainLoop */// private void mainLoop() {// while (true) {// try {// TimerTask task;// boolean taskFired;// synchronized(queue) {// // Wait for queue to become non-empty// while (queue.isEmpty() && newTasksMayBeScheduled)// queue.wait();// if (queue.isEmpty())// break; // Queue is empty and will forever remain; die//// // Queue nonempty; look at first evt and do the right thing// long currentTime, executionTime;// task = queue.getMin();// synchronized(task.lock) {// if (task.state == TimerTask.CANCELLED) {// queue.removeMin();// continue; // No action required, poll queue again// }// currentTime = System.currentTimeMillis();// executionTime = task.nextExecutionTime;// if (taskFired = (executionTime<=currentTime)) {// if (task.period == 0) { // Non-repeating, remove// queue.removeMin();// task.state = TimerTask.EXECUTED;// } else { // Repeating task, reschedule// queue.rescheduleMin(// task.period<0 ? currentTime - task.period// : executionTime + task.period);// }// }// }// if (!taskFired) // Task hasn't yet fired; wait// queue.wait(executionTime - currentTime);// }// if (taskFired) // Task fired; run it, holding no locks// task.run();// } catch(InterruptedException e) {// }// }// }}