I am really confused about this . Java has two Timer classes, one under swing , and one under util ... why is that? Which one should I use if I want to simply run X every Y seconds? Does this mean if I'm building a GUI I have to use the swing version for a timer?
thanks!
A Swing timer (an instance of javax. swing. Timer ) fires one or more action events after a specified delay. Do not confuse Swing timers with the general-purpose timer facility in the java. util package.
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions.
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
Here is the difference between javax.swing.Timer and java.util.Timer:
javax.swing.Timer
java.util.Timer
You can use Swing timers in two ways:
Here is the sources for above information http://www.javapractices.com/topic/TopicAction.do?Id=160 and http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
Which one should I use if I want to simply run X every Y seconds?
Depending upon what you are interacting with. If you are interacting with GUI then use javax.swing.Timer
, else use java.util.Timer
.
Does this mean if I'm building a GUI I have to use the swing version for a timer?
YES
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With