Java Timer and TimerTask

JavaJavaBeginner
Practice Now

Introduction

Java Timer and TimerTask are used to schedule tasks in the future. TimerTask is an abstract class that implements Runnable interface which helps to schedule tasks in Timer class. We can define a task using TimerTask class and schedule it using Timer class. Timer uses background threads for scheduling tasks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/class_methods -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/modifiers -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/oop -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/packages_api -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/identifier -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/operators -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/output -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/strings -.-> lab-117964{{"`Java Timer and TimerTask`"}} java/system_methods -.-> lab-117964{{"`Java Timer and TimerTask`"}} end

Import required packages

Import the required packages for Timer and TimerTask using the following code.

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

Create a task using TimerTask

Create a task to be executed using TimerTask class. Override the run() method to define the task to be performed. For instance, we can create a task to print "Hello, World!" as follows:

TimerTask task = new TimerTask() {
    public void run() {
        System.out.println("Hello, World!");
    }
};

Create a Timer object

Create a Timer object using the following code.

Timer timer = new Timer();

Schedule the task using Timer

Use the schedule() method of Timer class to schedule the task. For example, if we want to execute the task after 1000 milliseconds (one second), we can use the following code:

timer.schedule(task, 1000);

This will schedule the task to be executed after one second of delay.

Schedule the task to be repeated

We can also schedule a task to be executed repeatedly using the schedule() method with a delay and a period as parameters. In the following example, we schedule a task to print "Hello, World!" every 2 seconds, starting after a delay of 1 second.

timer.schedule(task, 1000, 2000);

Cancel the task

We can also cancel a scheduled task using the cancel() method of TimerTask class. In the following example, a task is scheduled to be executed just once and then canceled.

TimerTask task = new TimerTask() {
    public void run() {
        System.out.println("Task is being executed...");
        cancel();
    }
};
timer.schedule(task, 1000);

Use scheduleAtFixedRate() method

We can use the scheduleAtFixedRate() method to schedule a task to be executed at a fixed rate, irrespective of the completion time of the previous execution. For instance, we can schedule a task to print "Hello, World!" every 2 seconds, without regard to how long the task takes to execute, using the following code:

timer.scheduleAtFixedRate(task, 1000, 2000);

Use ExecutorService

We can use ExecutorService to schedule TimerTask objects. Here, we use ScheduledExecutorService to schedule a task. For instance, we can create a task to print "Hello, World!" every 2 seconds, using the following code:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(task, 1000, 2000, TimeUnit.MILLISECONDS);

Compile and run the code

Finally, compile and run the code using the following command in the terminal:

javac TimerTaskDemo.java && java TimerTaskDemo

Summary

In this lab, we learned how to use Java Timer and TimerTask to schedule and execute tasks at a specific time or delay. We also learned how to schedule a task to be repeated, cancel a task, use scheduleAtFixedRate() method, and use ExecutorService to schedule TimerTask objects.

Other Java Tutorials you may like