Timer : Java Glossary
home T words local find no local find frame, full screen Google search web for topic jump to footer translate with Babelfish 2008-04-13 by Roedy Green ©1996-2008 Canadian Mind Products
Go to : punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
Timer
If you want a task to be run at some time in the future or repeatedly at regular intervals, you can schedule it with the java.util.Timer class. This is more efficient than creating a Thread for the purpose and sleeping. java.util.Timer efficiently handles all such future events with a single thread. If the event you want to spawn takes a long time, it should spawn its own thread so as not to hold up other events being handled.

The whole idea of java.util.Timer is to avoid the overhead of creating a new Thread for every task. So there is only one Thread to handle all the tasks scheduled on a given Timer. That it why it must execute the tasks sequentially even if scheduled at the same time. If you want two tasks to run simulateously you will need to either spawn a separate task when the trigger happens or use two Timers.

java.util.Timer

javax.swing.Timer

javax.swing.Timer has similar capabilities. Use it only for GUI activities since the actions tie up the Swing thread, which is what you want for Swing method invocations. You don’t need SwingUtilities. invokeLater with javax.swing.Timer since it automatically dispatches the timer events on the Swing thread.

In JDK 1.5+ there is a an even more sophisticated timer called java.util.concurrent.ScheduledThreadPoolExecutor.

Long-Running Events

Timers work with a single Thread. That means your event must complete before the next event needs to be scheduled. If you have a very long running event to be scheduled, have your Timer event start a new Thread to run in the background in parallel with the Timer Thread.

Learning More

Sun’s Javadoc on java.util.Timer : available:
Sun’s Javadoc on javax.swing.Timer : available:
Sun’s Javadoc on the ScheduledThreadPoolExecutor class : available:

CMP_homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.18] Spread the Net
You are visitor number 26,912.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/Mindprod website mirror)
http://mindprod.com/jgloss/timer.html J:\mindprod\jgloss\timer.html