This paper mainly discusses the differences between Java.util.Timer's schedule (timertask,delay,period) and Scheduleatfixedrate (Timertask,delay,period).
Either of these functions, the timer is single-threaded, and the task is always executed within that single thread.
Four scenarios are discussed below:
[(Task 3s, interval 2s) + (task 2s, interval 3s)]x[schedule+scheduleatfixedrate]
Schedule, task 3s, interval 2s
NewTimer ().Schedule(NewTimerTask () {@Override Public void Run() {System. out.println(Thread.CurrentThread().GetName() +" "+Scheduledexecutiontime() / ++" "+ System.Currenttimemillis() / +);Try{Thread.Sleep( the); }Catch(Interruptedexception e) {e.Printstacktrace(); } } },0, -); output is timer-0 1519651551 1519651551Timer-0 1519651554 1519651554Timer-0 1519651557 1519651557
schedule, task 2s, interval 3s
Change the Thread.Sleep () in the above code to 2s and change the interval to 3s
Timer-0 1519651602 1519651602Timer-0 1519651605 1519651605Timer-0 1519651608 1519651608
Scheduleatfixedrate, task 3s, interval 2s
NewTimer ().scheduleatfixedrate(NewTimerTask () {@Override Public void Run() {System. out.println(Thread.CurrentThread().GetName() +" "+Scheduledexecutiontime() / ++" "+ System.Currenttimemillis() / +);Try{Thread.Sleep( the); }Catch(Interruptedexception e) {e.Printstacktrace(); } } },0, -); output is timer-0 1519651707 1519651707Timer-0 1519651709 1519651710Timer-0 1519651711 1519651713Timer-0 1519651713 1519651716
scheduleatfixedrate, task 2s, interval 3s
Timer-0 1519651750 1519651750Timer-0 1519651753 1519651753Timer-0 1519651756 1519651756
Summarize
Four names are defined below:
- Timer.scheduledexecutiontime () is a theoretical time interval
- System.currentmilliseconds () is the actual time interval
- The interval parameter in schedule (Task,delay,interval) and Scheduleatfixedrate (Task,delay,interval) is set time interval
- Task time: The time it takes to perform a task
Schedule () runtime, the theoretical interval is always equal to the actual time interval, which is max (task time, set interval)
Scheduleatfixedrate () runtime, the theoretical time interval is always equal to the set time interval, and the actual time interval is always equal to max (task time, Interval time).
Differences between the schedule () and schedualatfixedrate () functions of a timer in Java