Detailed explanation and example code of Java timer (timer, TimerTask)
Java timer
The two classes used to implement the timer function in Java are timer and TimerTask
Timer class is a class used to execute tasks. It accepts a TimerTask as a parameter
Timer has two modes of executing tasks. The most commonly used is schedule. It can execute tasks in two ways: 1: at a certain time (data) and 2: after a fixed time (int delay) Both methods can specify the frequency of task execution. This paper has two examples. One is simple, and the other uses internal classes
1. Simple example
Write a class first
Then write a class
In this way, a simple timer can be completed, but another way is to write these two classes into a class, that is, the inner class
2. Internal class
The difference between schedule and scheduleatfixedrate is that if the specified execution time is before the current system running time, scheduleatfixedrate will also execute the past time as a cycle, and schedule will not count the past time.
For example:
The interval is 3 minutes. The specified start time is 14:10:00 on December 30, 2005. If I execute this program at 14:17:00, it will be printed three times immediately
And note that the next execution is at 14:19 instead of 14:20. That is, the timing starts from the specified start time, not from the execution time.
However, if the schedule method is used above, the interval is 3 minutes, and the specified start time is 14:10:00 on December 30, 2005, then the program will be executed at 14:17:00, and the program will be executed once immediately. And the next execution time is 14:20, not the cycle from 14:10 (14:19).
Thank you for reading, hope to help you, thank you for your support to this site!