In the previous post, "Task Scheduler (i)--JDK timer", briefly introduced a timer, this article will share how to dynamically modify the schedule set by the timer.
First on the code:
Package Com.tgb.ccl.schema.dynamic;import java.util.date;/** * Dynamically modifiable tasks * * @author Arron * @date May 9, 2015 PM 1 : 52:15 * @version 1.0 */public class Dynamictimertask extends java.util.TimerTask {@Overridepublic void Run () {System.out.println ("---------start--------");D ate d = new Date (); for (int i=0;i<2;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.dynamic;import Java.util.calendar;import Java.util.date;import java.util.Timer;/** * Task Scheduler Manager * * @author Arron * @date May 9, 2015 PM 1:57:19 * @version 1.0 */public class Dynamictaskmanager {private static fi nal Long PERIOD = 5 * 1000;//5 Seconds/** * Singleton object */private static Dynamictaskmanager TaskManager = null;/** * Time Dispatch object */private Static Timer timer = new timer ();/** * Task */private static Dynamictimertask task = null;static {TaskManager = new dynamict Askmanager ();} 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 set time, the task = new Dynamictimertask () is executed immediately; Timer.schedule (task, starttime,period);} /** * Start timer */public void Start () {//Start task, 10 point 40 start task starting (Dateutils.booktime (10,40,0));} /** * Start timer */public void StArt (Long Preiod) {//Start task, 10 point 40 start task starting (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 ();} /** * Empty timer */public void clean () {if (task! = null) {Task.cancel ();} Timer.purge ();} /** * Stop task */public void Stop () {System.out.println ("--------task is stopping---------"); SYSTEM.OUT.PRINTLN ("---------task has 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 da te, 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 DateBooktime (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;}} @SuppressWarnings ("deprecation") public static void main (string[] args) {Dynamictaskmanager manager = Dynamictaskmanager.getinstance ();//Start the task, will be executed immediately, 2s when the execution is completed, 5s, the second execution, 7s when the second execution completed Manager.start (); for (int i=0;i<8;i + +) {try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ()}} 8s, stop original task, dynamic change start time manager.stop (); System.out.println ("Current time:" +new Date (). toLocaleString ()); System.out.println ("Modify original plan, re-execute after 5s"),//5s start again, i.e. 13s and then start Manager.start (Dateutils.addday (New Date (), Calendar.second, 5));}}
The results of the operation are as follows:
From the results, we can see that the original plan was started at 14:46:40, the second time in 14:46:45, each execution of 2s, that is, if the task is not changed, then the task will always be in 0s or 5s time execution. But in the main method, I closed the original task and then modified the start time to start a new task after 5s of the current time. The current time is 14:46:48,5s after the new plan is executed. This completes the dynamic modification of the task.
First of all, if you close the task, the Stop method completes this function. To do this, you must set the state of the task to cancel, and then call the timer's Purge method to remove all the tasks in the queue that have a status of cancel. This will not be executed until the execution time, because the task has already been removed. If you use the Cancel () method of the timer, all of the tasks in the timer are removed. Pay attention to this point.
In fact, when used in the project, it is more simple than this. Directly modify the StartTask () method, the start time and interval are taken from the database is OK. As long as you want to change the plan, first configure the start time and interval, and then write a restart method, call the clean and StartTask methods.
Someone asked me the difference between the timer and the quartz framework. Let me just say what I understand. After all, the timer is the JDK's own simple task scheduling tool class, with quartz is certainly the gap between shotgun and cannon. Quartz's configuration rules are more powerful, more capable of satisfying our complex needs, and allowing multiple threads, which is not comparable to a timer. If you need a very simple task Scheduler, then I think there is absolutely no need to use quartz. How to kill a chicken with sledgehammer?! If your business scenario is more complex, such as requiring the last business day of the 4th week of each month to perform settlement pay, if the last day is Saturday, it will be carried out one day in Friday. This scenario is easier than a timer with quartz.
However, the specific use, but also to see the project. There is no one who is more bull, only who is more suitable.
Task scheduling (ii)--JDK timer Dynamic modification of task execution plan