Tuesday, June 9, 2009

How to Implement a scheduler in java

Use java.util.Timer and java.util.TimerTask to Implement a scheduler in java.

The following are all the Timer methods you can use to schedule repeated executions of tasks:

schedule(TimerTask task, long delay, long period)
schedule(TimerTask task, Date time, long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

When scheduling a task for repeated execution, use one of the schedule methods when smoothness is important and a scheduleAtFixedRate method when time synchronization is more important.

schedule method is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run.

While in scheduleAtFixedRate, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."

Call Timer.cancel() to stop the Timer.

Example:

public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;

public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(),
0, //initial delay
1*1000); //subsequent rate
}

class RemindTask extends TimerTask {
int numWarningBeeps = 3;

public void run() {
if (numWarningBeeps > 0) {
toolkit.beep();
System.out.format("Beep!%n");
numWarningBeeps--;
} else {
toolkit.beep();
System.out.format("Time's up!%n");
//timer.cancel(); //Not necessary because
//we call System.exit
System.exit(0); //Stops the AWT thread
//(and everything else)
}
}
}
...
}

No comments:

Post a Comment