Usage of Timer class in Java
I will. util. timer and java. util. timerTask is collectively referred to as the Java timer framework, which enables programmers to easily plan simple tasks (note that these classes can also be used in j2s ). Before introducing this framework in Java 2 SDK, Standard Edition, and Version 1.3, developers must write their own scheduling programs, which requires a lot of effort to process threads and complex objects. wait () method. However, the Java timer framework does not have enough capacity to meet the planning requirements of many applications. Even a task that needs to be executed repeatedly at the same time every day cannot be planned directly using Timer, because a time jump occurs at the start and end of the Failover.
This article shows a generalTimerAndTimerTaskThe planning framework allows more flexible task scheduling. This framework is very simple-it includes two classes and one interface-and is easy to understand. If you are used to using the Java timer framework, you should be able to quickly master this planning framework.
Schedule a single task
The planning framework is based on the Java timer framework class. Therefore, before explaining how to use the planning framework and how to implement it, we will first look at how to use these classes for planning.
Imagine an egg timer. After a few minutes (when the egg is ready), it will sound to remind you. The code in Listing 1 forms the basic structure of a simple egg timer, which is written in Java:
Listing 1. eggtimer class
package org.tiling.scheduling.examples;import java.util.Timer;import java.util.TimerTask;public class EggTimer { private final Timer timer = new Timer(); private final int minutes; public EggTimer(int minutes) { this.minutes = minutes; } public void start() { timer.schedule(new TimerTask() { public void run() { playSound(); timer.cancel(); } private void playSound() { System.out.println("Your egg is ready!"); // Start a new thread to play a sound... } }, minutes * 60 * 1000); } public static void main(String[] args) { EggTimer eggTimer = new EggTimer(2); eggTimer.start(); }} |
EggTimerThe instance hasTimerInstance to provide the necessary plans. Usestart()Method after the egg timer is started, it plansTimerTaskIn minutes. It's time,TimerIt is called in the backgroundTimerTaskOfstart()Method To make it sound. The application stops when the timer is canceled.
Scheduled repeated tasks
By specifying a fixed execution frequency or a fixed execution interval,TimerYou can schedule repeated tasks. However, there are many applications that require more complex plans. For example, an alert clock that sends a wake-up ringtone at the same time every morning cannot simply use a fixed scheduled frequency of 86400000 milliseconds (24 hours ), it may be too late or too early to wake up when the clock is fast or slow (If your time zone uses clock. The solution is to use the calendar algorithm to calculate the next scheduled time of a daily event. This is exactly what the planning framework supports. ConsiderAlarmClockImplementation (for the source code of the planning framework and the JAR file containing the framework and example, see references ):
Listing 2. alarmclock class
package org.tiling.scheduling.examples;import java.text.SimpleDateFormat;import java.util.Date;import org.tiling.scheduling.Scheduler;import org.tiling.scheduling.SchedulerTask;import org.tiling.scheduling.examples.iterators.DailyIterator;public class AlarmClock { private final Scheduler scheduler = new Scheduler(); private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS"); private final int hourOfDay, minute, second; public AlarmClock(int hourOfDay, int minute, int second) { this.hourOfDay = hourOfDay; this.minute = minute; this.second = second; } public void start() { scheduler.schedule(new SchedulerTask() { public void run() { soundAlarm(); } private void soundAlarm() { System.out.println("Wake up! " + "It's " + dateFormat.format(new Date())); // Start a new thread to sound an alarm... } }, new DailyIterator(hourOfDay, minute, second)); } public static void main(String[] args) { AlarmClock alarmClock = new AlarmClock(7, 0, 0); alarmClock.start(); }} |
Note that this code is very similar to the egg timer application.AlarmClockThe instance hasScheduler(InsteadTimerInstances are used to provide the necessary plans. After the alarm is enabledSchedulerTask(InsteadTimerTask. This alarm is not used to schedule a task to be executed after a fixed delay, butDailyIteratorClass to describe its plan. Here, it only schedules tasks to be executed at every morning. The following is an output under normal operation:
Wake up! It's 24 Aug 2003 07:00:00.023Wake up! It's 25 Aug 2003 07:00:00.001Wake up! It's 26 Aug 2003 07:00:00.058Wake up! It's 27 Aug 2003 07:00:00.015Wake up! It's 28 Aug 2003 07:00:00.002... |
DailyIteratorImplementedScheduleIterator, This IsSchedulerTaskThe scheduled execution time of is specified as a seriesjava.util.DateObject interface. Thennext()Method iterations in chronological orderDateObject. Return ValuenullThis will cancel the task (that is, it will never run again)-in this case, an exception will be thrown when you try to schedule it again. Listing 3 containsScheduleIteratorInterface:
Listing 3. scheduleiterator Interface
package org.tiling.scheduling;import java.util.Date;public interface ScheduleIterator { public Date next();} |
DailyIterator Ofnext()Returns the valueDateObject, as shown in Listing 4. Thereforenext()Class callnext()Then, we will get the day of the date passed to the constructor or the am of the next day. Call againnext()Will return the AM of the next day, so repeated. To achieve this behavior,DailyIteratorUsedjava.util.CalendarInstance. The constructor adds a day to the calendar. This setting makes the first callnext()Will return the correctDate. Note that the Code does not explicitly mention the callback correction becauseCalendarImplementation (in this exampleGregorianCalendar.
Listing 4. dailyiterator class
package org.tiling.scheduling.examples.iterators;import org.tiling.scheduling.ScheduleIterator;import java.util.Calendar;import java.util.Date;/** * A DailyIterator class returns a sequence of dates on subsequent days * representing the same time each day. */public class DailyIterator implements ScheduleIterator { private final int hourOfDay, minute, second; private final Calendar calendar = Calendar.getInstance(); public DailyIterator(int hourOfDay, int minute, int second) { this(hourOfDay, minute, second, new Date()); } public DailyIterator(int hourOfDay, int minute, int second, Date date) { this.hourOfDay = hourOfDay; this.minute = minute; this.second = second; calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); calendar.set(Calendar.MILLISECOND, 0); if (!calendar.getTime().before(date)) { calendar.add(Calendar.DATE, -1); } } public Date next() { calendar.add(Calendar.DATE, 1); return calendar.getTime(); }} |
Implementation plan framework
In the previous section, we learned how to use the scheduler framework and compared it with the Java timer framework. Next, I will show you how to implement this framework. Except forScheduleIteratorInterface, there are two other classes that constitute this framework ――SchedulerAndSchedulerTask. These classes are actually used internallyTimerAndSchedulerTaskBecause the plan is actually a series of single-time timers. Listing 5 and 6 show the source code of these two classes:
Listing 5. Scheduler
package org.tiling.scheduling;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Scheduler { class SchedulerTimerTask extends TimerTask { private SchedulerTask schedulerTask; private ScheduleIterator iterator; public SchedulerTimerTask(SchedulerTask schedulerTask, ScheduleIterator iterator) { this.schedulerTask = schedulerTask; this.iterator = iterator; } public void run() { schedulerTask.run(); reschedule(schedulerTask, iterator); } } private final Timer timer = new Timer(); public Scheduler() { } public void cancel() { timer.cancel(); } public void schedule(SchedulerTask schedulerTask, ScheduleIterator iterator) { Date time = iterator.next(); if (time == null) { schedulerTask.cancel(); } else { synchronized(schedulerTask.lock) { if (schedulerTask.state != SchedulerTask.VIRGIN) { throw new IllegalStateException("Task already scheduled " + "or cancelled"); } schedulerTask.state = SchedulerTask.SCHEDULED; schedulerTask.timerTask = new SchedulerTimerTask(schedulerTask, iterator); timer.schedule(schedulerTask.timerTask, time); } } } private void reschedule(SchedulerTask schedulerTask, ScheduleIterator iterator) { Date time = iterator.next(); if (time == null) { schedulerTask.cancel(); } else { synchronized(schedulerTask.lock) { if (schedulerTask.state != SchedulerTask.CANCELLED) { schedulerTask.timerTask = new SchedulerTimerTask(schedulerTask, iterator); timer.schedule(schedulerTask.timerTask, time); } } } }} |
Listing 6 showsSchedulerTaskClass source code:
Listing 6. schedulertask
package org.tiling.scheduling;import java.util.TimerTask;public abstract class SchedulerTask implements Runnable { final Object lock = new Object(); int state = VIRGIN; static final int VIRGIN = 0; static final int SCHEDULED = 1; static final int CANCELLED = 2; TimerTask timerTask; protected SchedulerTask() { } public abstract void run(); public boolean cancel() { synchronized(lock) { if (timerTask != null) { timerTask.cancel(); } boolean result = (state == SCHEDULED); state = CANCELLED; return result; } } public long scheduledExecutionTime() { synchronized(lock) { return timerTask == null ? 0 : timerTask.scheduledExecutionTime(); } }} |
Just like the egg timer,SchedulerEach instance hasTimerIs used to provide the underlying plan.SchedulerA single timer is not used as when the timer is implemented. It concatenates a group of single timers so thatScheduleIteratorRun at specified timeSchedulerTaskClass.
ConsiderationsSchedulerPublicschedule()Method-this is the entry point of the plan because it is the method called by the customer (the only other public method described in the cancel task Sectioncancel()). By callingScheduleIteratorInterfacenext(), Found that the first executionSchedulerTask. Then, by calling the underlying layerTimerClass per timeschedule()Method. The start plan is executed at this time. Provided for a single executionTimerTaskThe object is embedded.SchedulerTimerTaskClass, which encapsulates tasks and iterator ). Call the embedded class at the specified timerun()Method, which uses the wrapped task and iterator reference to reschedule the next execution of the task.reschedule()Method andschedule()The method is very similar, but it is private, and the execution of a group is slightly differentSchedulerTaskStatus check. The rescheduling process repeats repeatedly and creates a new embedded class instance for each execution plan until the task or scheduler is canceled (or the JVM is disabled ).
SimilarTimerTask,SchedulerTaskIn its lifecycle, it must go through a series of States. After it is created, it is inVIRGINStatus, which indicates that it has never been scheduled. After the plan, it becomesSCHEDULEDStatus, and then cancel the task using one of the methods described below, it becomesCANCELLEDStatus. Manage the correct status change-if you do not want a non-VIRGINStatus Task is scheduled twice-addedSchedulerAndSchedulerTaskClass complexity. When performing operations that may change the task status, the Code must synchronize the Lock Object of the task.
Cancel task
There are three methods to cancel a scheduled task. The first is to callSchedulerTaskOfcancel()Method. This is similar to callingTimerTaskOfcancel()Method: The task will no longer run, but the task already runningStillThe operation is complete.cancel()The Return Value of the method is a Boolean value, indicating that if no call is madecancel()Then, whether the scheduled task will run. More accurately, if the task is calledcancel()PreviouslySCHEDULEDStatus, then it returnstrue. If you try to schedule a canceled (or even scheduled) task againSchedulerWill throwIllegalStateException.
The second way to cancel a scheduled task isScheduleIteratorReturnnull. This is only the first method to simplify the operation, becauseSchedulerClass callSchedulerTaskClasscancel()Method. If you want to use an iterator instead of a task to control the scheduled stop time, you can use this method to cancel the task.
The third method is to callcancel()Method to cancel the entireScheduler. This will cancel all the tasks of the program debugging and make it unable to schedule any more tasks.
Extended cron Utility
The planning framework can be compared to the UNIXcronUtilities, except that the number of planned times is mandatory rather than declarative. For exampleAlarmClockUsed in implementationDailyIteratorClass, its plan andcronJobs have the same plan.0 7 * * *Startcrontab(These fields specify minutes, hours, days, months, and weeks respectively ).
However, the planning frameworkcronMore flexible. Imagine opening hot water in the morningHeatingControllerApplication. I would like to instruct it to "Open hot water at AM every workday and open hot water at AM every week ". Usecron, I need twocrontabItem (0 8 * * 1,2,3,4,5And0 9 * * 6,7). And useScheduleIteratorThe solution is more concise, because I can use composition to define a single iterator. Listing 7 shows one of the methods:
Listing 7. Using Composite to define a single iterator
int[] weekdays = new int[] { Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY }; int[] weekend = new int[] { Calendar.SATURDAY, Calendar.SUNDAY }; ScheduleIterator i = new CompositeIterator( new ScheduleIterator[] { new RestrictedDailyIterator(8, 0, 0, weekdays), new RestrictedDailyIterator(9, 0, 0, weekend) } ); |
RestrictedDailyIteratorSimilarDailyIteratorBut it is restricted to running only on a specific day of the week, whileCompositeIteratorClass to obtain a groupScheduleIteratorS, and arrange the date correctly in a single plan ..
There are many planscronCannot be generated,ScheduleIteratorBut it can. For example, the plan described on the last day of each month can be implemented using the standard Java calendar algorithm (CalendarClass ).cronIt cannot be expressed. Applications do not even need to be usedCalendarClass. In the source code of this article, I added an example of a safety light controller, which runs according to the "turn on the light 15 minutes before sunset" plan. This implementation uses the Calendrical Calculations Software Package to calculate the local Sunset Time (given longitude and latitude.
Real-time assurance
When writing an application of a usage plan, you must understand the time guarantee of the framework. Is my task executed ahead of schedule or delayed? If there is advance or delay, what is the maximum deviation? Unfortunately, there are no simple answers to these questions. However, in practice, its behavior is sufficient for many applications. The following discussion assumes that the system clock is correct (for information about the Network Time Protocol, see references ).
BecauseSchedulerDelegate a planTimerClass,SchedulerReal-time assurance andTimer.TimerUseObject.wait(long)Method to schedule tasks. The current thread will wait until it is awakened, which may be due to one of the following reasons:
- The
notify()OrnotifyAll()Method.
- The thread is interrupted by another thread.
- Without notice, the thread is awakened (calledSpurious wakeup, Joshua BlochValid Java Programming Language GuideIn this book, Item 50 describes it-see references ).
- The specified time has reached.
ForTimerClass.wait()The object is private. Even so,TimerThe implementation still protects the first three reasons for early wakeup, which ensures that the thread is awakened only after the specified time. Currently,Object.wait(long)It will wake up before and after the specified time, so the thread may wake up in advance. In this example,TimerWill make anotherwait()Run (scheduledExecutionTime - System.currentTimeMillis()) Milliseconds to ensureThe task will never be executed in advance.
Will the task be delayed? Yes. There are two main causes for delayed execution: thread plan and garbage collection.
The Java language specification intentionally does not strictly define the thread plan. This is because the Java platform is universal and applicable to a wide range of hardware and related operating systems. Although most JVM implementations have fair Thread Scheduling programs, this is not guaranteed-of course, each implementation has a different policy for allocating the processor time to the thread. Therefore, whenTimerWhen a thread wakes up after the allocated time, the time it actually executes its tasks depends on the JVM thread plan policy and how many other threads compete for the processor time. Therefore, to reduce the latency of tasks, you should minimize the number of running threads in the application. To achieve this, you can consider running the scheduler in a separate JVM.
For large applications that create a large number of objects, the JVM spends a lot of time on garbage collection (GC. By default, the entire application must wait for it to complete GC, which may take several seconds or even longer (JavaCommand line options for application starters-verbose:gcWill cause every GC event to be reported to the console ). To minimize the GC-caused pause (which may affect the execution of quick tasks), minimize the number of objects created by the application. Similarly, it is helpful to run the plan code in a separate JVM. At the same time, you can try several fine-tuning options to minimize GC pause. For example, incremental GC will try to distribute the primary collection cost to several small collections. Of course this will reduce GC efficiency, but this may be an acceptable price for the time plan.
When will I be scheduled?
If the task itself can monitor and record all instances with delayed execution, it is helpful to determine whether the task can run on a running basis.SchedulerTaskSimilarTimerTask, There isscheduledExecutionTime()Method, which returns the last execution time of the scheduled task. Inrun()When the method startsSystem.currentTimeMillis() - scheduledExecutionTime()To determine how long the task is delayed (in milliseconds ). This value can be recorded to generate a statistics on the distribution of delayed execution. You can use this value to determine what actions the task should take-for example, if the task is too late, it may not do anything. If the application requires more strict time guarantee, you can refer to the Real-Time Java specification.
Conclusion
In this article, I introduced a simple enhancement of the Java timer framework, which makes flexible planning policies possible. The new framework is actually more common.cron-In factcronImplemented asScheduleIteratorTo replace Javacron, Which is very useful. Although strict real-time assurance is not provided, this framework can be used by many general Java applications that require scheduled tasks.