Task Scheduling (2) -- jdk's built-in Timer dynamically modifies the task execution plan, and jdktimer

Source: Internet
Author: User

Task Scheduling (2) -- jdk's built-in Timer dynamically modifies the task execution plan, and jdktimer

In the previous blog titled "Task Scheduling (1) -- the built-in Timer of jdk", we briefly introduced Timer. This article will share how to dynamically modify the plan formulated by Timer.


First run the Code:

Package com. tgb. ccl. schema. dynamic; import java. util. date;/*** jobs that can be dynamically modified ** @ author arron * @ date May 9, 2015 1:52:15 * @ version 1.0 */public class DynamicTimerTask extends java. util. timerTask {@ Overridepublic void run () {System. out. println ("--------- start --------"); Date d = new Date (); for (int I = 0; I <2; 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. dynamic; 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 9, 2015 * @ version 1.0 */public class DynamicTaskManager {private static final long PERIOD = 5*1000; // 5 seconds/*** singleton object */private static DynamicTaskManager taskManager = null;/*** Time Scheduling object */private static Timer timer = new Timer (); /*** task */pr Ivate static DynamicTimerTask task = null; static {taskManager = new DynamicTaskManager ();} public static DynamicTaskManager getInstance () {if (taskManager = null) {taskManager = new DynamicTaskManager ();} return taskManager;} public DynamicTaskManager () {}@ SuppressWarnings ("deprecation") public void startTask (Date startTime, long period) {System. out. println ("set start time:" + startTime. toLocaleString (); // if the current time exceeds The task = new DynamicTimerTask (); timer. schedule (task, startTime, period);}/*** start timer */public void start () {// start the task, start the task at (DateUtils. bookTime (, 0);}/*** start timer */public void start (long preiod) {// start the task, start the task at (DateUtils. bookTime (10, 40, 0), preiod);}/*** start timer */public void start (Date startTime) {start (startTime, PERIOD );} /*** start timer */public void start (Date startTime, long Preiod) {startTask (startTime, preiod);}/*** restart */public void restart () {clean (); start ();} /*** clear timer */public void clean () {if (task! = Null) {task. cancel ();} timer. purge ();}/*** stop task */public void stop () {System. out. println ("-------- the task is stopping ---------"); clean (); System. out. println ("--------- the task has been stopped ----------");} static class DateUtils {/*** increase or decrease the number of days ** @ param date * @ param CalendarFlag * value Calendar. DAY_OF_MONTH, Calendar. HOUR_OF_DAY, * Calendar. MINUTE, Calendar. SECOND, Calendar. MILLISECOND * @ param num * @ return */public static Date addDay (Date date, int CalendarFlag, int num) {Calendar startDT = Calendar. getInstance (); startDT. setTime (date); startDT. add (CalendarFlag, num); return startDT. getTime ();}/*** set time ** @ param hour * @ param minute * @ param second * @ return */public static 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); Date date = calendar. getTime (); return date ;}@suppresswarnings ("deprecation") public static void main (String [] args) {DynamicTaskManager manager = DynamicTaskManager. getInstance (); // start the task. The task is executed once immediately. The task is executed at 2 seconds, the task is executed at 5s, and the manager is executed at 7 seconds. start (); for (int I = 0; I <8; I ++) {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}}// when 8 s, stop the original task and dynamically change the start time manager. stop (); System. out. println ("current time:" + new Date (). toLocaleString (); System. out. println ("modify the original plan, re-execute after 5s"); // restart after 5s, that is, restart manager at 13 s. start (DateUtils. addDay (new Date (), Calendar. SECOND, 5 ));}}

The running result is as follows:


From the results, we can see that the original plan started at 14:46:40, and the second was at 14:46:45, each execution of 2 s, that is to say, if you do not change the task plan, the task will always be executed within 0 s or 5 s. However, in the main method, I disabled the original task and modified the start time. The new task will be started five seconds later. The current time is 14:46:48, and the new plan is executed after 5s. This completes the dynamic modification of the task.


First, if the task is disabled, the stop method completes this function. To stop running a task, you must set the task status to cancel and then call the purge method of timer to remove all tasks in the queue whose status is cancel. In this way, even when the execution time is reached, the task will not be executed because it has been removed. If the cancel () method of timer is used, all tasks of timer are removed. Pay attention to this.


In fact, it is easier to use it in projects. Directly modify the startTask () method. The start time and interval are all retrieved from the database. You only need to configure the start time and interval when you want to change the plan, then write a restart method by yourself, and call the clean and startTask methods.


Someone asked me the difference between Timer and Quartz framework. Let me explain my understanding. After all, Timer is a simple task scheduling tool class provided by jdk. Compared with Quartz, Timer is definitely a shotgun and cannon. The Quartz configuration rules are more powerful, which can better meet our complex needs and allow multithreading, which is not comparable to Timer. If you need simple task scheduling, I don't think it is necessary to use Quartz. How can it be used ?! If your business scenario is complex, for example, you need to settle the salary on the last workday of the first week of every month, if the last day is Saturday, it will be executed on the premise day and on the Friday. In this scenario, Quartz is easier than Timer.


However, you still need to check the project. No one is better, and only one is better.


Related Article

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.