Last Updated:

Java Timer and TimerTask Example

Java Timer and TimerTask. Theory

A class is a utility class and can be used to delay a thread at a specific time. The Java Timer class can be used for a scheduled task that will need to be executed once or run regularly at a specific time.java.util.Timer

A class is an abstract class that implements the Runnable interface. We should inherit from this class by creating our own TimerTask.java.util.TimerTask

  • A class is thread-safe, so multiple threads can share a single object without the need for external synchronization.TimerTimer
  • The Timer class is used to perform tasks at regular intervals.java.util.TaskQueue
  • Only one TimerTask thread can be executed at a time. For example, if you create a Timer that should run every 10 seconds, but it takes a full 20 seconds for a single thread to run, the Timer object will add tasks to the queue until one thread finishes executing it. As soon as it has served its 20 seconds, the queue will be notified and the next thread from this queue will start working.

The Timer class uses the wait() and notify() methods to schedule tasks.

Java Timer and TimerTask. Practice

Let's look at the use in Java using an example:TimerTimerTask

Note that a single thread will run for 20 seconds, and the Timer object is scheduled to run every 10 seconds. Here is the result of the program:

The result of the execution confirms that if the task is already running, timer will wait until the end. When he has finished one task, he will immediately start the next task from the queue.

Use the Timer method to complete the timer and not to perform any scheduled tasks. However, this does not prevent him from letting him finish the current task. If the timer is running in the daemon, it will be terminated as soon as all user threads have finished executing.cancel()

The Timer class contains several methods to schedule a task to run once at a specified time or to run regularly with a specific delay. There are several methods for periodically running a task at a certain interval.schedule()scheduleAtFixedRate()

That's all you need to know about working with Java Timer and TimerTask in Java.