Using the Timer and TimerTask Classes

   

Using the Timer and TimerTask Classes

The Timer and TimerTask classes are brand new to SDK 1.3. Most developers would admit to having created classes similar to these two classes time and time again in their applications. So, it's nice to see them being included in the core API.

The Timer class provides a facility for threads to schedule tasks to be completed in the future by a background thread. The tasks can be scheduled for a one-time execution or repeated execution at some interval cycle. A system might create multiple Timer instances, each one having a thread that runs in the background executing the tasks one by one. If the task was set up to execute just once, then after that task completed, it would no longer be executed by the Timer thread. By default, the Timer thread does not run as a daemon thread. So, the Timer thread would keep an application running, as it is an actual user thread by default. You can, of course, make the Timer thread a daemon thread. This would allow the application to exit if it was the only thread running.

One of the nice features about the Timer class is that it is thread-safe. Multiple threads can share a single Timer object without having to have any synchronization of its own.

The partner to the Timer class is the TimerTask. This is the task that is scheduled with the Timer object. The TimerTask class provides an abstract run method that must be overridden and include the behavior to execute when the task is scheduled to run. There is also a cancel method on the TimerTask that will cause the task to stop executing. If the task has not executed yet or scheduled with the Timer object, the cancel method guarantees that it will never run. If it is a repeating task, then it will never run, unless it is in the middle of execution. In that case, after execution is completed, it is guaranteed never to run again. The cancel method returns a boolean value. If the canceling of the task prevented at least one execution from happening, then the return value will be true. If the cancel method was called after the task has completed and it was a one-time execution, the return value will be false.

Listing 11.20 shows an example of extending the TimerTask class.

Listing 11.20 Source Code for MyTask.java
 import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MyTask extends TimerTask {   int maxNumberOfTimesToRun = 0;   // A reference to a date object   Date currentDateTime = null;   static int counter = 1;   Timer myTimer = null;   // Default Constructor   public MyTask( int maxCounter, Timer aTimer )   {     super();     maxNumberOfTimesToRun = maxCounter;     myTimer = aTimer;   }   // Override the abstract method  run()   public void run()   {     if ( MyTask.counter <= maxNumberOfTimesToRun )     {       System.out.println( MyTask.counter );       // Create a current date instance       currentDateTime = new Date( System.currentTimeMillis() );       // Display the current date object as a string       System.out.println( "MyTask: " + currentDateTime.toString() );       MyTask.counter++;     }     else     {       // Since we reached the counter max, cancel the task       cancel();       // Also cancel the timer since I'm the only one using it.       // This might not be true in all cases       myTimer.cancel();     }   } } 

Listing 11.21 is the main class that creates the Timer object, schedules the MyTask class from Listing 11.20 with the Timer, and starts the Timer moving.

Listing 11.21 Source Code for MyTaskMain
 import java.util.Timer; public class MyTaskMain {   // This is the main method that starts the Timer. Notice we did not have to   // call a start method on the Timer. It actually associates a thread with   // each Timer instance   public static void main(String[] args)   {     Timer timer = new Timer();     MyTask task = new MyTask( 5, timer );     // Schedule the task to run every 3,000 millisecs or 3 seconds starting     // right from the beginning.     timer.schedule( task, 0, 3000 );   } } 

Here's the output from running the MyTaskMain class in Listing 11.21:

 C:\jdk1.3se_book\classes>java MyTaskMain 1 MyTask: Mon Jul 03 22:19:58 PDT 2000 2 MyTask: Mon Jul 03 22:20:01 PDT 2000 3 MyTask: Mon Jul 03 22:20:04 PDT 2000 4 MyTask: Mon Jul 03 22:20:07 PDT 2000 5 MyTask: Mon Jul 03 22:20:10 PDT 2000 C:\jdk1.3se_book\classes> 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net