Java Timer Class



Introduction

The Java Timer class provides facility for threads to schedule tasks for future execution in a background thread.

  • This class is thread-safe i.e multiple threads can share a single Timer object without the need for external synchronization.

  • This class schedules tasks for one-time execution, or for repeated execution at regular intervals.

  • All constructors start a timer thread.

Class declaration

Following is the declaration for java.util.Timer class −

public class Timer extends Object

Class constructors

Sr.No. Constructor & Description
1

Timer()

This constructor creates a new timer.

2

Timer(boolean isDaemon)

This constructor creates a new timer whose associated thread may be specified to run as a daemon.

3

Timer(String name)

This constructor creates a new timer whose associated thread has the specified name.

4

Timer(String name, boolean isDaemon)

This constructor creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

Class methods

Sr.No. Method & Description
1 void cancel()

This method terminates this timer, discarding any currently scheduled tasks.

2 int purge()

This method removes all cancelled tasks from this timer's task queue.

3 void schedule(TimerTask task, Date time)

This method schedules the specified task for execution at the specified time.

4 void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

This method schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

Methods inherited

This class inherits methods from the following classes −

  • java.util.Object

Scheduling a Task to Execute using Timer Example

The following example shows the usage of Java Timer schedule(TimerTask, Date) method to schedule a timer operation. We've created a timer object using a CustomTimerTask object. CustomTimerTask is custom class extending TimerTask class and implements the run() method which will execute at scheduled time. Then we created a timer object and scheduled a task using schedule() to execute task now.

Open Compiler
package com.tutorialspoint; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TimerDemo { public static void main(String[] args) { // creating timer task, timer TimerTask tasknew = new CustomTimerTask(); Timer timer = new Timer("test",true); // scheduling the task timer.schedule(tasknew, new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Error"); } } } class CustomTimerTask extends TimerTask { @Override public void run() { System.out.println("working on"); } }

Output

Let us compile and run the above program, this will produce the following result.

working on
Advertisements