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.
Following is the declaration for java.util.Timer class −
public class Timer extends ObjectClass constructors Sr.No. Constructor & Description 1
Timer()
This constructor creates a new timer.
2Timer(boolean isDaemon)
This constructor creates a new timer whose associated thread may be specified to run as a daemon.
3Timer(String name)
This constructor creates a new timer whose associated thread has the specified name.
4Timer(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 Methods inheritedThis class inherits methods from the following classes −
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.
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4