In general, the priority is quartz> scheduledthreadpoolexecutor> timer.
Method |
Scheduling Method |
Thread mode |
Exception Handling |
Timer (not recommended) |
Based on absolute time, tasks are sensitive to system time changes. |
All timertasks are executed in a single thread. If a timertask is time-consuming, the execution of other timertasks is affected. |
Timertask does not capture unchecked exceptions thrown by timertask. Therefore, when an exception is thrown, Timer terminates, causing the unexecuted timertask to stop executing. |
Scheduledthreadpoolexecutor |
Based on relative time. This also means that the requirement "Please help me execute mytask at every day" cannot be implemented. |
Construct a fixed thread pool to execute tasks |
Properly handled, without affecting the execution of other tasks |
Quartz |
Job + trigger. A job is an executable task that can be scheduled. A trigger can schedule a job. It can process absolute time & relative time. |
The thread pool size can be specified. |
Properly handled, without affecting the execution of other tasks |
1. Timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
private int i=0;
@Override
public void run() {
System.out.println("Round " + i++);
}
}, 0, 5000);//5s
2. scheduleatfixedrate ()
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(5);
pool.scheduleAtFixedRate(new Runnable() {
private int i=0;
@Override
public void run() {
System.out.println("Round " + i++);
}
}, 0, 5, TimeUnit.SECONDS);
3. Quartz
Look at Classroom 2: http://www.cnblogs.com/alipayhutu/archive/2012/06/05/2536617.html
Http://www.ibm.com/developerworks/cn/java/j-quartz/
Http://www.opensymphony.com/quartz/
Http://blog.csdn.net/szwangdf/article/details/6158646
Http://blog.csdn.net/masterseventeen/article/details/3443114