1. TimerTask:
- 存在的缺陷:若执行的任务超时,会导致,定时只能在任务之后完成之后,才能接着执行。
private static void useTimerTask() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task : " + System.currentTimeMillis());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timer.schedule(task, 0, 1000);
}
2. ScheduleService
- 定时任务规则:若任务执行时间大于定时时间间隔, 则按照任务执行时间来不断执行。
private static void testScheduleAtFixedRate() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(
() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName());
}, 1, 2, TimeUnit.SECONDS);
}
- API
- setContinueExistingPeriodicTasksAfterShutdownPolicy:设置为true时,调用了
shutdown()
,依然会定时的去执行任务。 - setExecuteExistingDelayedTasksAfterShutdownPolicy:当调用
shutdown()
时,退出执行的任务。