A Java Timer is a useful utility class that allows you to schedule a task for future execution. The Timer creates a background thread and waits for a specified amount of time before executing the task. The Task may be repeatable or scheduled for a specific date. To create a task using the Timer class, simply create an instance of TimerTask. The run() method contains code that triggers the scheduled task.The schedule method is part of the Timer class and schedules a given task.

When you want to cancel a task, you can use the purge() method. This method removes the cancelled tasks from the Timer’s queue and frees up memory. The call to this method is rare, and most programs will never need it. It is only needed for a few applications.

import java.util.*;
public class TimerDemo {
    public static void main(String[] args) {
        Timer timer = new Timer(  );
        TimerTask task = new TimerTask(  ) {
            public void run(  ) {
                System.out.println("Timer Demo");
        timer.schedule( task, 500);