First, Scheduledexecutorservice design thought
Scheduledexecutorservice is a timed task class based on thread pool design, where each dispatch task is assigned to a thread in the thread pool to execute, that is, the task is executed concurrently and does not affect each other.
It is important to note that Scheduledexecutorservice only actually starts a thread when the dispatch task comes, and the rest of the time Scheduledexecutorservice is out of the state of the polling task.
1. Thread Tasks
class Implements Runnable { private String jobName; Myscheduledexecutor () { } myscheduledexecutor (String jobName) { this. JobName= jobName; } @Override publicvoid run () { + ' is running ');} }
2. Scheduled Tasks
Public Static voidMain (string[] args) {Scheduledexecutorservice service= Executors.newscheduledthreadpool (10); LongInitialDelay = 1; LongPeriod = 1; //1 seconds from now, once every 1 seconds job1Service.scheduleatfixedrate (NewMyscheduledexecutor ("Job1"), InitialDelay, period, timeunit.seconds); //2 seconds from now, once every 2 seconds job2Service.schedulewithfixeddelay (NewMyscheduledexecutor ("Job2"), InitialDelay, period, timeunit.seconds); }
Two of the most commonly used scheduling methods in Scheduledexecutorservice are Scheduleatfixedrate and Schedulewithfixeddelay. Scheduleatfixedrate Each execution time is pushed back one time interval for the last task, that is, each execution time is: InitialDelay, Initialdelay+period, Initialdelay+2*period, ... Schedulewithfixeddelay each execution time pushes back one time interval for the last task end, that is, each execution time is: InitialDelay, Initialdelay+executetime+delay, Initialdelay+2*executetime+2*delay. Therefore,Scheduleatfixedrate is based on fixed time interval for task scheduling, Schedulewithfixeddelay depends on the duration of each task execution , is based on the time interval of the task scheduling.
Reference documents:
http://www.ibm.com/developerworks/cn/java/j-lo-taskschedule/
Java timed Task Interface Scheduledexecutorservice