Friday, June 16, 2023

What is Timer and TimerTask in Java – Tutorial Example

In Java, the Timer and TimerTask classes are used for scheduling tasks to be executed at a specified time or after a specific interval. These classes provide a convenient way to perform time-based operations in Java applications. This tutorial will introduce you to the Timer and TimerTask classes and demonstrate their usage through an example.


Timer Class

The Timer class in Java provides a facility for scheduling tasks to be executed at a specified time or after a certain delay. It is part of the java.util package and was introduced in JDK 1.3. The Timer class internally uses a single background thread to execute scheduled tasks.


To use the Timer class, you need to create an instance of it and schedule tasks using its schedule() or scheduleAtFixedRate() methods. The schedule() method is used to schedule a task to be executed once, while the scheduleAtFixedRate() method is used to schedule a task to be executed repeatedly at fixed intervals.


TimerTask Class

The TimerTask class is an abstract class that represents a task to be scheduled by a Timer. To use the TimerTask class, you need to create a subclass and override its run() method. The run() method contains the code that will be executed when the task is triggered.


Example: Scheduling a Task

Let's see an example that demonstrates how to use the Timer and TimerTask classes to schedule a task in Java:


import java.util.Timer;
import java.util.TimerTask;

public class TaskScheduler {
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task executed!");
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 5000); // Schedule the task to be executed after 5 seconds
    }
}

In the above example, we create a TimerTask subclass by overriding its run() method, which simply prints "Task executed!" to the console. We then create an instance of the Timer class and schedule the task using the schedule() method, specifying a delay of 5000 milliseconds (5 seconds). 

When you run this program, it will wait for 5 seconds and then execute the task, printing "Task executed!" to the console. 

Cancelling a Task 

If you want to cancel a scheduled task before it is executed, you can use the Timer class's cancel() method. 

Here's an example that demonstrates task cancellation:


import java.util.Timer;
import java.util.TimerTask;

public class TaskScheduler {
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task executed!");
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 5000); // Schedule the task to be executed after 5 seconds

        // Cancel the task after 3 seconds
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                task.cancel();
                System.out.println("Task cancelled!");
            }
        }, 3000);
    }
}

In this example, we schedule a task to be executed after 5 seconds, but we also schedule another task to cancel the first task after 3 seconds. When you run this program, you will see that "Task cancelled!" is printed to the console before "Task executed!" because the cancellation task runs earlier. 

Conclusion 

The Timer and TimerTask classes in Java provide a convenient way to schedule tasks to be executed at specific times or after certain intervals. By using these classes, you can

No comments:

Post a Comment