Examples of timer and TimerTask timers and timed tasks in Java

These two classes are very convenient to use and can meet most of our needs for timers

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

TimerTest.Java:

Such Runtime:

One second after the program is started, print "-" - "-" - "-" on the console, and then execute the run() method of mytask after an interval of two seconds. Print "-" - "-" - "-" - "so as to keep the cycle. When the s character is entered on the console, the timer will cancel the work, jump out of the whole cycle, and the program will end!

TimerTest2.java:

This class creates two scheduled tasks mytask1 and mytask2

The mytask1 task is used in the same way as the example in the TimerTest class above. That is, the specified task is scheduled to be executed repeatedly with a fixed delay after the specified delay.

The mytask2 task is different from the above usage. Timer.scheduleatfixedrate is executed by the scheduleatfixedrate () method of timer timer.

The scheduleatfixedrate() method is defined in API 1.6.0 as follows:

Schedule the specified task to be repeated at a fixed rate at the specified time. Subsequent execution is performed at approximately fixed time intervals separated by specified cycles.

An approximately fixed time interval means that in a fixed rate execution, each execution is scheduled relative to the scheduled initial execution time. If an execution is delayed for any reason (such as garbage collection or other background activities), two or more executions will occur quickly and continuously, so that subsequent executions can catch up.

Other common methods of timer class:

cancel()

Terminate this timer and discard all currently scheduled tasks.

purge()

Remove all cancelled tasks from the task queue of this timer.

schedule(TimerTask task,Date time)

Schedule to perform the specified task at the specified time.

Other common methods of TimerTask class:

cancel()

Cancel this timer task.

run()

The action to be performed by this timer task.

scheduledExecutionTime()

Returns the scheduled execution time of the most recent actual execution of this task.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

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
分享
二维码
< <上一篇
下一篇>>