Scheduling Recurring Tasks In Java Applications
By Tom White
2004-01-23
Reader Rating:

Extending the cron facility
The scheduling framework could be likened to the UNIX cron facility, except that the specification of scheduling times is controlled imperatively rather than declaratively. For example, the DailyIterator class used in the implementation of AlarmClock has the same scheduling as a cron job, specified by a crontab entry beginning 0 7 * * *. (The fields specify minute, hour, day of month, month, and day of week, respectively.)
However, the scheduling framework has more flexibility than cron. Imagine a HeatingController application that switches the hot water on in the mornings. I would like to instruct it to "turn the hot water on at 8:00 AM on weekdays and 9:00 AM on weekends." Using cron, I would need two crontab entries (0 8 * * 1,2,3,4,5 and 0 9 * * 6,7). By using a ScheduleIterator, the solution is more elegant because I can define a single iterator using composition. Listing 7 shows one way to do this:
Listing 7. Using composition 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)
}
);
|
RestrictedDailyIterator class is like DailyIterator, except it is restricted to run on particular days of the week; and a CompositeIterator class takes a set of ScheduleIterators and correctly orders the dates into a single schedule. See Resources for the source code to these classes.
There are many other schedules that cron cannot produce, but an implementation of ScheduleIterator can. For instance, the schedule described by "the last day of every month" can be implemented using standard Java calendar arithmetic (using the Calendar class), whereas it is impossible to express this using cron. Applications don't even have to use the Calendar class. In the source code for this article (see Resources), I have included an example of a security light controller that runs to the schedule "turn the lights on 15 minutes before sunset." The implementation uses the Calendrical Calculations Software Package (see Resources) to compute the time of the sunset locally (given the latitude and longitude).
First published by IBM developerWorks
If you found this article interesting, you may want to read these as well:
» Build and Implement A Single Sign-On Solution
» Eye On Performance: A Load Of Stress
» A Brief History Of Garbage Collection
|