JWS-121 Added new scheduler utility classes so that usage statistics and service...
[jabaws.git] / webservices / compbio / stat / servlet / util / SchedulerTask.java
1 package compbio.stat.servlet.util;
2
3 import java.util.TimerTask;
4
5
6 /**
7  * A task that can be scheduled for recurring execution by a {@link Scheduler}.
8  */
9 public abstract class SchedulerTask implements Runnable {
10
11     final Object lock = new Object();
12
13     int state = VIRGIN;
14     static final int VIRGIN = 0;
15     static final int SCHEDULED = 1;
16     static final int CANCELLED = 2;
17
18     TimerTask timerTask;
19
20     /**
21      * Creates a new scheduler task.
22      */
23
24     protected SchedulerTask() {
25     }
26
27     /**
28      * The action to be performed by this scheduler task.
29      */
30
31     public abstract void run();
32
33     /**
34      * Cancels this scheduler task.
35      * <p>
36      * This method may be called repeatedly; the second and subsequent calls have no effect.
37      *
38      * @return true if this task was already scheduled to run
39      */
40
41     public boolean cancel() {
42         synchronized (lock) {
43             if (timerTask != null) {
44                 timerTask.cancel();
45             }
46             boolean result = (state == SCHEDULED);
47             state = CANCELLED;
48             return result;
49         }
50     }
51
52     /**
53      * Returns the <i>scheduled</i> execution time of the most recent actual execution of
54      * this task. (If this method is invoked while task execution is in progress,
55      * the return value is the scheduled execution time of the ongoing task execution.)
56      *
57      * @return the time at which the most recent execution of this task was scheduled
58      * to occur, in the format returned by <code>Date.getTime()</code>. The return value
59      * is undefined if the task has yet to commence its first execution.
60      */
61
62     public long scheduledExecutionTime() {
63         synchronized (lock) {
64             return timerTask == null ? 0 : timerTask.scheduledExecutionTime();
65         }
66     }
67
68 }