Task Scheduling (1) -- jdk's built-in Timer and jdktimer

Source: Internet
Author: User

Task Scheduling (1) -- jdk's built-in Timer and jdktimer

Speaking of task scheduling, you may think of the Quartz framework, but the simple task scheduling tool class that comes with jdk does not know much about it. I think if your business is relatively simple, there is no need to use Quartz or other frameworks, and Timer is fully qualified. Here is a brief introduction to Timer.


Timer is a Timer tool provided by jdk. When used, it starts a separate thread outside the main thread to execute the specified scheduled task. It can be executed once or repeatedly multiple times.

TimerTask is an abstract class that implements the Runnable interface and represents a task that can be executed by Timer.


I used TimerTask to create a task. In the run method, the task scheduling logic is used. Use a Timer object to schedule tasks.


First, a simple example is provided:

Package com. tgb. ccl. schema; import java. util. date; import java. util. timerTask;/*** tasks that cannot be dynamically modified ** @ author arron * @ date 1:52:15 on January 1, May 7, 2015 * @ version 1.0 */public class FixedTimerTask extends TimerTask {@ Overridepublic void run () {Date d = new Date (); for (int I = 0; I <3; I ++) {try {Thread. sleep (1, 1000); System. out. println ("executed [" + (I + 1) + "] seconds, at:" + d. toLocaleString ();} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println ("this task scheduling ends, at:" + new Date (). toLocaleString (); System. out. println ("---------------------------");}}

Package com. tgb. ccl. schema; import java. util. calendar; import java. util. date; import java. util. timer; /*** Job Scheduling manager ** @ author arron * @ date 1:57:19 on January 1, May 7, 2015 * @ version 1.0 */public class TaskManager {// private static final long PERIOD = 5*60 * 1000; // 5 minutes private static final long PERIOD = 5*1000; // 1 second public TaskManager () {Timer timer = new Timer (); FixedTimerTask task = new FixedTimerTask (); system. out. println ("start"); // 0 indicates immediate execution, and timer will be executed every other time. schedule (task, 0, PERIOD); // 1000 indicates that the task is executed once in one second, and then executed once every other time. // timer. schedule (task, 1000, PERIOD); // 0 indicates immediate execution, and will be executed once every other time. // timer. schedule (task, 1000, PERIOD); // It is executed once at on the same day and no longer executed // timer. schedule (task, bookTime (15, 0, 0); // It is executed at on the same day. It will be executed at intervals of time. // if the time exceeds the set time, will be executed once immediately // timer. schedule (task, bookTime (0, 34, 10), PERIOD); // timer. scheduleAtFixedRate (task, bookTime (, 0), PERIOD);} private Date bookTime (int hour, int minute, int second) {Calendar ar calendar = Calendar. getInstance (); calendar. set (Calendar. HOUR_OF_DAY, hour); calendar. set (Calendar. MINUTE, minute); calendar. set (Calendar. SECOND, second); Date date = calendar. getTime (); return date;} public static void main (String [] args) {new TaskManager ();}}

You only need to execute the main method to test it.


You may have noticed that the schedule method of timer is overloaded. There must be a TimerTask instance. If the second parameter is of the long type, this parameter indicates the delay time, in milliseconds. If the value is 1000, the task is scheduled in 1 second. If it is of the Date type, it indicates the time when the task starts to be executed. When the time reaches this time point, the task will automatically start scheduling. Of course, if the current time has exceeded the set start time, it will be executed immediately. The third parameter is an optional parameter, which is a long parameter, indicating the scheduling interval. If this parameter is set, the task is scheduled repeatedly. Otherwise, it will be executed only once. This parameter is still in milliseconds.


If you pay attention to it, you will find that timer not only provides the schedule method, but also provides the scheduleAtFixedRate method. Both methods are Task Scheduling Methods. What are their differences?


The difference is that when the current time has exceeded the set execution time, the schedule method will be executed immediately, the second execution is calculated based on the current execution time + interval (of course, when the task execution time exceeds the interval, the second execution will be performed immediately after the first execution is completed ). The scheduleAtFixedRate method is also executed immediately, but the second execution is performed according to (current execution time-set time) /interval to calculate the number of executions from the set time to the present.


For example, the task scheduling needs to be executed for 2 s, the interval is 10 s, and I set the task to be executed at 8 points. The current time is 08:00:10. If it is the schedule method, It will be executed once immediately, and the second execution time will be 08:00:20. If it is the scheduleAtFixedRate method, It will be executed once immediately, and the calculation can be performed once from 08:00:10 to 08:00:00, so it will be executed again immediately at 08:00:12, the third execution is performed at 08:00:20 and then every 10 s.


(The test result of the schedule method is shown on the left, and the test result of the scheduleAtFixedRate method is displayed on the right)

This is not exactly what many people on the Internet say. But I tested it. I cannot test the results they said. Which one do you trust? You have tried it on your own.


Next I will share with you how to dynamically modify the Timer scheduling plan.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.