How to schedule a Task in Java
In Java to run/execute a task periodically or at some interval, we can use the TimerTask
class from its java.util
package. TimerTask
is an abstract class that implements Runnable
interface.
For example, you have to print the current date and time every second or make an API call every second.
Related Post: Spring Task Scheduler Example using @Scheduled Annotation
Follow the below steps to schedule a task.
Step 1: Create a class and extend TimerTask
.
class MyTask extends TimerTask
Step 2: Override its run()
method and define your task inside the run()
method which needs to be executed.
@Override
public void run() {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date & time is: " + now);
}
Step 3: Now create another class to run the task and instantiate Timer
object.
Timer timer = new Timer();
Step 4: Assign scheduled task through Timer.shedule()
method.
timer.schedule(new MyTask(), 0, 1000);
See the complete example.
TaskScheduler.java
package org.websparrow.timer;
import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;
public class TaskScheduler {
public static void main(String[] args) {
// Initialize the Timer object
Timer timer = new Timer();
// Schedule the task which execute on every 1 second interval
timer.schedule(new MyTask(), 0, 1000);
}
}
class MyTask extends TimerTask {
// Define your task
@Override
public void run() {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date & time is: " + now);
}
}
Output:
Current date & time is: 2022-11-19T14:01:57.856926100
Current date & time is: 2022-11-19T14:01:58.851819600
Current date & time is: 2022-11-19T14:01:59.863210100
Current date & time is: 2022-11-19T14:02:00.873723300
Current date & time is: 2022-11-19T14:02:01.885005100
Current date & time is: 2022-11-19T14:02:02.895217600
Current date & time is: 2022-11-19T14:02:03.906639800
Current date & time is: 2022-11-19T14:02:04.915792600
Current date & time is: 2022-11-19T14:02:05.928842400