Sie sind auf Seite 1von 4

java.util.

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.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend
this class to create our own TimerTask that can be scheduled using java Timer class.
Timer class is thread safe and multiple threads can share a single Timer object without need for
external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval
and at any time there can be only one thread running the TimerTask, for example if you are creating
a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object
will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and
another thread will start executing.
Timer class uses Object wait and notify methods to schedule the tasks.

Timer in Java is a utility class form java.util package which provides facility to schedule task at any time
in future. As I said earlier, Timer is analogues to alarm clock you setup in your smartphone. Just like alarm
can be either one time or recurring, You can also schedule task for one time and recurring time interval using
Timer API. Timer provides method to schedule Task where task is instance of TimerTask class, which
implements Runnable interface and overrides run() method to define task which is called on scheduled
time.

How Timer works in Java
Timer class in Java maintains a background Thread (this could be either daemon thread or user thread, based on
how you created your Timer object), also called as timer's task execution thread. For each Timer there would be
corresponding task processing Thread which run scheduled task at specified time. If your Timer thread is not daemon
then it will stop your application from exits until it completes all schedule task. Its recommended that TimerTask
should not be very long otherwise it can keep this thread busy and not allow other scheduled task to get completed.
This can delay execution of other scheduled task, which may queue up and execute in quick succession once
offending task completed.


Difference between Timer and TimerTask in Java
I have seen programmers getting confused between Timer and TimerTask, which is quite unnecessary because
these two are altogether different. You just need to remember:

1) Timer in Java schedules and execute TimerTask which is an implementation of Runnable interface and
overrides run method to defined actual task performed by that TimerTask.

2) Both Timer and TimerTask provides cancel() method. Timer's cancel() method cancels whole timer while
TimerTask's one cancels only a particular task. I think this is the wroth noting difference
between Timer and TimerTask in Java.

Canceling Timer in Java
You can cancel Java Timer by calling cancel() method of java.util.Timer class, this would result in following:
1) Timer will not cancel any currently executing task.
2) Timer will discard other scheduled task and will not execute them.
3) Once currently executing task will be finished, timer thread will terminate gracefully.
4) Calling Timer.cancel() more than one time will not affect. second call will be ignored.

In addition to cancelling Timer, You can also cancel individual TimerTask by using cancel() method
of TimerTask itself.


Important points on Timer and TimerTask in Java
Now we know what is Timer and TimerTask in Java, How to use them, How to cancel then and got an
understanding on How Timer works in Java. Its good time to revise Timer and TimerTask.

1.One Thread will be created corresponding ot each Timer in Java, which could be either daemon or user thread.
2.You can schedule multiple TimerTask with one Timer.
3.You can schedule task for either one time execution or recurring execution.
4.TimerTask.cancel() cancels only that particular task, while Timer.cancel() cancel all task scheduled in
Timer.
5.Timer in Java will throw IllegalStateException if you try to schedule task on a Timer which has been
cancelled or whose Task execution Thread has been terminated.

The output confirms that if a task is already executing, Timer will wait for it to finish and once
finished, it will start again the next task from the queue.
Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method
is used to terminate the timer and discard any scheduled tasks, however it doesnt interfere with the
currently executing task and let it finish. If the timer is run as daemon thread, whether we cancel it or
not, it will terminate as soon as all the user threads are finished executing.
Timer class contains several schedule() methods to schedule a task to run once at given date or after
some delay. There are several scheduleAtFixedRate() methods to run a task periodically with certain
interval.
While scheduling tasks using Timer, you should make sure that time interval is more than normal
thread execution, otherwise tasks queue size will keep growing and eventually task will be executing
always.


Timer and TimerTask example to schedule Tasks
Here is one example of Timer and TimerTask in Java to implement Reminder utility.

public class JavaReminder {
Timer timer;

public JavaReminder(int seconds) {
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new RemindTask(), seconds*1000); //delay in
milliseconds
}

class RemindTask extends TimerTask {

@Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
timer.cancel(); //Not necessary because we call System.exit
//System.exit(0); //Stops the AWT thread (and everything else)
}
}

public static void main(String args[]) {
System.out.println("Java timer is about to start");
JavaReminder reminderBeep = new JavaReminder(5);
System.out.println("Remindertask is scheduled with Java timer.");
}
}

Output
Java timer is about to start
Remindertask is scheduled with Java timer.
ReminderTask is completed by Java timer //this will print after 5 seconds



MyTimerTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.journaldev.threads;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

@Override
public void run() {
System.out.println("Timer task started at:"+new Date());
completeTask();
System.out.println("Timer task finished at:"+new Date());
}

private void completeTask() {
try {
//assuming it takes 20 secs to complete the task
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

public static void main(String args[]){
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
Notice that one thread execution will take 20 seconds but Timer object is scheduled to run the task
every 10 seconds. Here is the output of the program:
TimerTask started
Timer task started at:Wed Dec 26 19:16:39 PST 2012
Timer task finished at:Wed Dec 26 19:16:59 PST 2012
Timer task started at:Wed Dec 26 19:16:59 PST 2012
Timer task finished at:Wed Dec 26 19:17:19 PST 2012
Timer task started at:Wed Dec 26 19:17:19 PST 2012
Timer task finished at:Wed Dec 26 19:17:39 PST 2012
Timer task started at:Wed Dec 26 19:17:39 PST 2012
Timer task finished at:Wed Dec 26 19:17:59 PST 2012
Timer task started at:Wed Dec 26 19:17:59 PST 2012
Timer task finished at:Wed Dec 26 19:18:19 PST 2012
Timer task started at:Wed Dec 26 19:18:19 PST 2012
TimerTask cancelled
Timer task finished at:Wed Dec 26 19:18:39 PST 2012
The output confirms that if a task is already executing, Timer will wait for it to finish and once
finished, it will start again the next task from the queue.

Das könnte Ihnen auch gefallen