Home > Java > javaTutorial > body text

How can we implement a timer thread in Java?

WBOY
Release: 2023-08-30 14:49:04
forward
1033 people have browsed it

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!");
   }
}
Copy after login

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!
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!