Timer:
java.util.Timer
is a utility class that provides facility for threads to schedule tasks for
future execution in a background thread. Tasks may be scheduled for one-time
execution, or for repeated execution at regular intervals.
TimerTask:
A
task that can be scheduled for one-time or repeated execution by a Timer.
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.
Run a reminder timer
task after a certain time period
import java.util.Timer;
import java.util.TimerTask;
public class TimerTaskExample {
Timer timer;
public TimerTaskExample(int
seconds) {
timer = new Timer();
long millis = seconds * 1000;
timer.schedule(new TaskReminder(), millis);
}
class TaskReminder extends TimerTask {
public void
run() {
System.out.println("Timer Task is executing..!");
/*
* TimerTask.cancel() method is used to
* terminate the Time Task.
*/
timer.cancel();
System.out.println("Timer Task Finished..!");
}
}
public static void main(String args[]) {
System.out.println("Timer Task scheduled");
int reminder_time = 3;
new TimerTaskExample(reminder_time);
System.out.println("It will execute after 3 sec...");
}
}
Output:
Timer Task scheduled
It will execute after
3 sec...
Timer Task is
executing..!
Timer Task
Finished..!
Perform timer task
repeatedly
import
java.util.Timer;
import
java.util.TimerTask;
public class
RepeatTimerTaskExam {
Timer timer;
public RepeatTimerTaskExam(long intialDelay,long subsequentRate){
timer = new Timer();
timer.schedule(new TaskReminder(),intialDelay,subsequentRate);
}
class
TaskReminder extends TimerTask {
int loop = 5;
public void run() {
if (loop > 0) {
System.out.println("Timer task, Repeat# "+ loop);
loop--;
} else {
timer.cancel();
System.out.println("Timer task.. Finished!");
}
}
}
public static void main(String
args[]) {
long intialDelay = 0; // time to
start first Task
long subsequentRate = 1000; // delay subsequent Task.
new RepeatTimerTaskExam(intialDelay, subsequentRate);
System.out.println("Task scheduled...");
}
}
Output:
Task scheduled...
Timer task, Repeat# 5
Timer task, Repeat# 4
Timer task, Repeat# 3
Timer task, Repeat# 2
Timer task, Repeat# 1
Timer task.. Finished!
No comments:
Post a Comment