When there is a need to trigger a task automatically based on time we should schedule it using a timer api. The requirement can vary from a single execution on a fixed time to high complex recurring event. For example take our regular alarm clock where we fix a time and it beeps coming day on the fixed time. Similarly a high complex example would be the MS outlook where we can schedule events with a different combination.
Following are the things in consideration
So coming up with a nice scheduler api is a quite challenging task. You can consider this as a project for a summer. I know people will jump on and point out numerous existing apis and say why re-invent the wheel? I really hate the jargon re-inventing the wheel, its one of the most misused one. When Google came into market, there were already established players in the field like Yahoo!, Lycos, Ask Jeeves, Alta Vista. But they did a fantastic job and came to top. When you do something of good quality there is always takers for it, do not worry if it is already existing or not. But try to work towards better than the existing.
Considering schedulers in java, we have the wonderful Quartz api. If we want to try something from JDK itself, in util package we have Timer and TimerTask and these were available from JDK 1.3 It is a no-nonsense, sleek and simple to use api. Comparison between this utility and Quartz would be un fair. Quartz supports trillions of possibilities and one of the most used open source schedulers. I have committed plan to write a series of articles on Quartz in future then we can explore it in detail.
This api provides two important variations that needs to be noted.
Each task execution is scheduled relative to the actual execution time of the previous execution. So what is actual execution? This says that, there is no guarantee that the task will be executed at the pre-planned time and it may be delayed due to garbage collection or some background activity.
We should also not confuse with triggering of task and completion of task. Triggering is the moment at which the Timer fires start a task. If a thread is asked to send email, it may wait for access to the resource like mail server. Only after the email is sent this task is considered to be completed. We need to have this duration in mind when we schedule recurrence tasks. If the recurrence time is shorter and already the previous task is not completed, the subsequent tasks will join the queue.
Here each recurring tasks are scheduled relative to the start time of the timer. If there is any delay in execution subsequent executions will occur in quick succession to catch up with the original scheduled time. In previous case, subsequent execution will depend on just previous execution time.
The difference between these two can be easily observed using the below sample program by observing the output.
package com.javapapers.thread; import java.util.Timer; public class TimerPiano { Timer dingTimer; Timer dongTimer; public TimerPiano(int ding,int dong) { dingTimer = new Timer(); dingTimer.schedule(new Sound("Ding!"), ding * 1000, ding * 1000); //dingTimer.scheduleAtFixedRate(...); dongTimer = new Timer(); dongTimer.schedule(new Sound("Dong!"), dong * 1000, dong * 1000); //dongTimer.scheduleAtFixedRate(...); } public static void main(String args[]) { new TimerPiano(2,4); } }
package com.javapapers.thread; import java.awt.Toolkit; import java.util.TimerTask; public class Sound extends TimerTask { Toolkit toolkit; String sound; public Sound(String sound) { this.sound = sound; //toolkit = Toolkit.getDefaultToolkit(); } public void run() { System.out.println(sound); //toolkit.beep(); } }
ScheduledExecutorService is a latest api available from JDK 1.5 onwards and we can see about that in a coming article.
Comments are closed for "Java Timer".
Thanks for posting good article. I tried to execute this code from command prompt. There is a compiler error while compiling TimerTask class saying that “can’t find symbol Sound”.
I have compiled Sound source and a Sound class exists in the same folder where I’m trying to compile the TimerPiano class. If you get time please guide me. Even I have removed the package statements from both the source files and tried.
Another great article by you . Thanks a lot. i already go through your Design Pattern series . Wish to see more on that . And waiting for Multi Threading (most confusing to me) article .
it’s good. post a article like How marker interface works.i mean internal architecture of marker interface…
Thanks
Another nice informative article. But
Can we use run method without extending Thread class or implementing Runnable interface.
@Rahul Pareek:
“Run” method comes from the “java.lang.Runnable” interface. In the current case, java.util.TimerTask(An abstract class) implements the “Runnable” interface. In the given code “Sound” class extends the “TimerTask” and overrides the run method.
all your articles are informative and simple to understand…keep going god bless your work
Hey I tried the code…….nothing problem with that……..executed….but sound is not coming…….
Great article. Tried a long time to figure out how to do delays like this. Works like a charm. But how do I make it run once and not recurring?
I also forgot to ask: How do I stop the timer? For instance after 5 times or after a key is pressed.
Hi, I tried to execute the given example(I uncommented the toolkit statements) but could not hear any beep sound . help me regarding this…
Hi,
I faced the same problem too…
I uncommented the toolkit statement but I couldn’t hear the beep sound help me regarding this…
Waiting for your tutorial of quartz.
Good luck.
Joseph Please could you tell me the
difference bwetween quartz scheduler and timertask scheduler of Java default
May be u guys have kept ur computers in mute else u r using jdk1.2 lolzzz. Else this code works perfectly fine. And once the sound starts, it continues until u forcefully stop it. Nice one!
Quartz is supreme. A dedicated open source scheduler API providing sophisticated scheduling options.
Timertask is JDK’s own API, a simple with minimal features.
[…] java.util.Timer uses the mediator design pattern. […]
Will a timer scheduled to run every 24 hours run even if server stops or restarts?
This article is really wonderful. It properly describes the function of Java Timer class.
Nice great article. How to do for one time execution job? that is with a start time and end time. I dont want to repeat my job?