Use of Java timer

1、 Concept

2、 Precautions for timer class

1. To create a timer object is to start a new thread, but the newly started thread is not a daemon thread. It always runs in the background. You can set the newly started timer thread as a daemon thread through the following steps.

new Timer(true);

2. Advance: when the planned time is earlier than the current time, the task will be run immediately.

3. Delay: TimerTask runs one by one in a queue, so the execution time may be inconsistent with your expected time. Because the previous task may take a long time, the running time of the subsequent task will be delayed. The specific start time of the delayed task is based on the "end time" of the previous task

4. Periodic run: timer Schedule (TimerTask task, date, firsttime, long period) executes the task every millisecond from the firsttime:

5. The current time of schedule (TimerTask task, long delay) is the reference time. Based on this time, the TimerTask task is executed once after delaying the specified number of milliseconds.

7. What is the difference between timer's cancel() and TimerTask's cancel()?

As mentioned earlier, tasks are executed one by one in sequence in the form of columns. TimerTask Cancel () refers to canceling the current task from the task pair column. Timer. The value of cancel () cancels all tasks in the current task queue. It is worth noting that timer's cancel() sometimes does not necessarily stop executing the planned task, but executes normally. This is because the cancel () method in the timer class sometimes does not compete for the queue lock, so the tasks in the TimerTask class continue to execute normally.

3、 What is the difference between scheduleatfixedrate and schedule

Similarities:

1. Both the method schedule and the method scheduleatfixedrate are executed sequentially, so non thread safety is not considered.

2. Method schedule and method scheduleatfixedrate if the execution time of the task is not delayed, the execution time of the next task is calculated by referring to the "start" time of the previous task.

3. Method schedule and method scheduleatfixedrate if the execution time of the task is delayed, the execution time of the next task is calculated by referring to the time at the end of the previous task.

difference:

There is basically no difference in the use of method schedule and method scheduleatfixedrate, that is, scheduleatfixedrate has catch-up execution. What does it mean? If a task is interrupted during periodic running, scheduleatfixedrate will try to make up the previously dropped task for running. The schedule doesn't matter, and then run the next task. You can refer to this blog, which is very vivid.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>