A simple demo that uses java.util.Timer to schedule a task to execute after every 3 seconds:
import java.util.Timer;
import java.util.TimerTask;
public class Scheduler {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("hello");
}
};
timer.schedule(task,0,3000);
Thread.sleep(100000);
}
}
Write your code in public void run() method that you want to execute periodically.
The following are all the Timer methods you can use to schedule repeated executions of tasks:
- schedule(TimerTask task, long delay, long period)
- schedule(TimerTask task, Date time, long period)
- scheduleAtFixedRate(TimerTask task, long delay, long period)
- scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Canceling Timer in Java
You can cancel Java Timer by calling cancel() method of java.util.Timer class.
But keep in mind that:
- Timer will not cancel any currently executing task.
- Timer will discard other scheduled task and will not execute them.
- Once currently executing task will be finished, timer thread will terminate gracefully.
- Calling Timer.cancel() more than one time will not affect. second call will be ignored.