Home  >  Article  >  Java  >  How can we implement a timer thread in Java?

How can we implement a timer thread in Java?

WBOY
WBOYforward
2023-08-30 14:49:041009browse

How can we implement a timer thread in Java?

Timer class schedules a task to run once or repeatedly at a given time. It can also run in the background as a daemon thread. To associate a Timer with a daemon thread, use a constructor with a Boolean value. Timers schedule tasks with fixed delay and fixed rate. Under fixed delay, if any one execution is delayed by the system GC, the other executions are also delayed, and each execution is delayed corresponding to the previous execution. At fixed rate, if any execution is delayed by System GC, 2-3 executions occur in succession to cover the fixed rate corresponding to the first execution start time. The Timer class provides the cancel() method to cancel the timer. When this method is called, the timer expires. The Timer class only performs tasks that implement TimerTask.

Example

import java.util.*;
public class TimerThreadTest {
   public static void main(String []args) {
      Task t1 = new Task("Task 1");
      Task t2 = new Task("Task 2");
      Timer t = new Timer();
      t.schedule(t1, 10000); <strong>//  executes for every 10 seconds</strong>
      t.schedule(t2, 1000, 2000); <strong>// executes for every 2 seconds</strong>
   }
}
class Task extends TimerTask {
   private String name;
   public Task(String name) {
       this.name = name;
   }
   public void run() {
      System.out.println("[" + new Date() + "] " + name + ": task executed!");
   }
}

Output

[Thu Aug 01 21:32:44 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:46 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:48 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:50 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:52 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:53 IST 2019] Task 1: task executed!
[Thu Aug 01 21:32:54 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:56 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:58 IST 2019] Task 2: task executed!
[Thu Aug 01 21:33:00 IST 2019] Task 2: task executed!

The above is the detailed content of How can we implement a timer thread in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete