Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Aug 19, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Schedule Events with The Timer Class

Scheduling recurrent or future events can be a hassle, but the Timer class can make it a lot easier. With a couple of simple calls, you can create any number of scheduled or recurring events.

Timers are created with a simple constructor and then called with one of the schedule() methods to set an actual task. Tasks are defined by subclassing the TimerTask class and implementing a run() method that will be called when the scheduled event is reached. TimerTask implementations can be anonymous, as is done in this example:
java.util.Timer timer = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask()

   public void run() {/*insert task code here*/}

You can create three types of schedules: delay schedules, repeating schedules, and fixed-delay schedules. Delay schedules simply prompt an event to occur once at a specific future time. The code snippet below illustrates a task being scheduled to execute after 10 seconds have elapsed:

Repeating or fixed-rate schedules will prompt events to repeat once per each elapsed period (even if that means that tasks will queue up) and ensure that all events occur as closely as possible to their scheduled times. For example, the following code snippet creates a schedule that will execute its task once for every elapsed second, starting immediately:

A fixed-delay timer places the emphasis on ensuring that the indicated delay always elapses between invocations. This example will schedule a task to recur with at least a second delay between invocations, starting immediately:

Each Timer instance runs its tasks in a single thread, so if you want tasks to execute completely independently, you should create a new Timer object for each task. You can assign multiple tasks to a single Timer, but only one task can run at once. Therefore, multiple timer tasks can delay each other from their scheduled execution times.
Ramneek Handa
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date