Task Scheduler (i)--jdk the timer that comes with it

Source: Internet
Author: User

When it comes to task scheduling, you might think of the quartz framework, but the Simple Task Scheduler tool class that comes with the JDK doesn't know much about people. I think if your business is relatively simple, there is no need to use quartz and other frameworks, using a timer can be fully competent. Simply to share the timer I know.


The timer is a timer tool provided in the JDK that uses a single thread that executes the specified scheduled task outside the main thread, and can be executed once or repeatedly.

TimerTask is an abstract class that implements the Runnable interface, representing a task that can be performed by a timer.


I use TimerTask to create a task in which the Run method is the logic of task scheduling. Use a Timer object to schedule the task.


Let's start with a particularly simple example:

Package Com.tgb.ccl.schema;import java.util.date;import java.util.timertask;/**  * Task not dynamically modified *  * @author Arron * @date May 7, 2015 PM 1:52:15  * @version 1.0  */public class Fixedtimertask extends timertask{@Overridepublic void R Un () {Date d = new Date (); for (int i=0;i<3;i++) {try {thread.sleep (1000); SYSTEM.OUT.PRINTLN ("executed" + (i+1) + "" Seconds, at: "+d.tolocalestring ());} catch (Interruptedexception e) {e.printstacktrace ();}} SYSTEM.OUT.PRINTLN ("This task is scheduled to end, at:" +new Date (). toLocaleString ()); System.out.println ("---------------------------");}}

Package Com.tgb.ccl.schema;import java.util.calendar;import Java.util.date;import java.util.timer;/** * Task Scheduler Manager * * @  Author Arron * @date May 7, 2015 PM 1:57:19 * @version 1.0 */public class TaskManager {//private static final long PERIOD = 5 * 60 * 1000;//5 minutes private static final Long PERIOD = 5 * 1000;//1 seconds Public TaskManager () {Timer timer = new timer (); Fixedtimertask task = new Fixedtimertask (); System.out.println ("Start");//0 represents an immediate execution once, Timer.schedule (task, 0, PERIOD) is executed once every other time,//1000 is executed after 1 seconds, and is executed once every other time Timer.schedule (Task, PERIOD),//0 means executing once,//timer.schedule (task, N, PERIOD) once every other time, and/or 14:4 on the same day, executed once , the//timer.schedule (task, Booktime (15,0,0)) is no longer executed, and/or is executed once at 14:4 on the same day, and once every time after time is executed///if it exceeds the set time, it will be executed once// Timer.schedule (Task, Booktime (0,34,10), PERIOD);//timer.scheduleatfixedrate (Task, Booktime (0,40,0), PERIOD);} Private Date booktime (int hour, int minute, int second) {Calendar calendar = calendar.getinstance (); Calendar.set (Calendar . Hour_of_day, HOUR); Calendar.set (calendar.minUTE, minute); Calendar.set (Calendar.second, SECOND);D ate Date = Calendar.gettime (); return date;} public static void Main (string[] args) {new TaskManager ();}}

You can test it as long as you execute the main method.


As you may have noticed, the schedule method of the timer is overloaded. Parameters have to have a timertask instance. If the second parameter is a long, this parameter represents the delay time, in milliseconds. If 1000, that is 1 seconds after the Task Scheduler. A date type indicates the time at which the task starts executing. When the time arrives, 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 that represents the time interval for scheduling. If this parameter is available, the task is a recurring dispatch. Otherwise, it will only be executed once. This parameter is still measured in milliseconds.


If you look at it a little bit, you'll find that the timer not only provides the schedule method, but also provides the Scheduleatfixedrate method. Both of these methods are task scheduling methods, what is the difference between them?


The difference is that when the current time has exceeded the set execution time, the schedule method executes immediately, and the second execution is calculated by the current execution time + interval (although the task execution time exceeds the interval, the second time is executed immediately after the first execution). The Scheduleatfixedrate method is also executed immediately, but its second execution is to calculate how many times it will be executed from the set time to the present (the current execution time-set time)/time interval.


For example: The Task Scheduler needs to execute 2s, the interval time is 10s, I set the 8 point execution. The current time is 8 points 0 minutes 10 seconds, if the schedule method is executed immediately, the second execution time is 08:00:20. If it is the Scheduleatfixedrate method, it will be executed once, and then the 08:00:10-08:00:00 can be executed once, so it will be executed again at 08:00:12, and the third execution is performed at 08:00:20. Every 10s is executed at a later time.


(The left figure is the test effect of the schedule method, the right figure is the test effect of the Scheduleatfixedrate method)

This is not the same as many people on the internet say. But this is my test. The kind of results they say I can't measure anyway. You know exactly what you believe, and you'll be clear if you try it yourself.


The next article to share how to dynamically modify the timer schedule, please look forward to.

Task Scheduler (i)--jdk the timer that comes with it

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.