Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to schedule specific task to perform functionality later.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Create a class Time that extends java.util.TimerTask and override the run() method with the task logic (printing the time).
  2. In main, instantiate a java.util.Timer.
  3. Call ob.schedule(t, 3000) to schedule the TimerTask to 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 Timer and TimerTask classes 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)
ADVERTISEMENT