Java Program to schedule specific task to perform functionality later.
Objective
Write a Java program to schedule a task to run automatically after a delay.
Algorithm / Approach
- Create a class
Timethat extendsjava.util.TimerTaskand override therun()method with the task logic (printing the time). - In main, instantiate a
java.util.Timer. - Call
ob.schedule(t, 3000)to schedule theTimerTaskto execute exactly once after a 3000ms (3 second) delay.
Test.java
import java.util.Timer;
import java.util.TimerTask;
class Test {
public static void main(String[] args) {
Timer ob = new Timer();
Time t = new Time();
ob.schedule(t,3000);
}
}
class Time extends TimerTask {
public void run(){
Date d = new Date();
String time = String.format("%tr",d);
System.out.print(time);
}
}
Expected Output
//print time after 3 seconds 11:30:43 PM
Explanation of the Program
- The
TimerandTimerTaskclasses provide a simple background thread scheduling framework. - This is highly useful for tasks like auto-saving data, session timeouts, or polling a server. While you can schedule one-off tasks (as seen here), you can also use
scheduleAtFixedRate()to run tasks repeatedly forever.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)