Scheduledexecutorservice Interface
Based on executorservice, scheduledexecutorservice provides the time-based task execution function. It provides the following methods:
Schedule (task, initdelay): schedules submitted callable or runnable tasks to be executed after the time specified by initdelay.
Scheduleatfixedrate (): Schedule the submitted runnable tasks to be executed repeatedly at the specified interval.
Schedulewithfixeddelay (): Schedule the submitted runnable task to be executed again after each execution, waiting for the time specified by delay.
Code: Example of scheduleexecutorservice
Import java. util. Concurrent. callable;
Import java. util. Concurrent. executionexception;
Import java. util. Concurrent. executors;
Import java. util. Concurrent. scheduledexecutorservice;
Import java. util. Concurrent. scheduledfuture;
Import java. util. Concurrent. timeunit;
Public class scheduledexecutorservicetest
{
Public static void main (string [] ARGs) throws interruptedexception, executionexception
{
// * 1
Scheduledexecutorservice service = executors. newscheduledthreadpool (2 );
// * 2
Runnable task1 = new runnable ()
{
Public void run ()
{
System. Out. println ("taskrepeating .");
}
};
// * 3
Final scheduledfuture future1 = service. scheduleatfixedrate (task1, 0, 1, timeunit. Seconds );
// * 4
Scheduledfuture future2 = service. Schedule (New callable ()
{
Public String call ()
{
Future1.cancel (true );
Return "taskcancelled! ";
}
}, 10, timeunit. Seconds );
System. Out. println (future2.get ());
// * 5
Service. Shutdown ();
}
}
In this example, there are two tasks. The first task prints "taskrepeating" every second, and the second task cancels the first task after five seconds.
* 1: initialize a scheduledexecutorservice object. The thread pool size of this object is 2.
* 2: defines a runnable task using an internal function.
* 3: Call the defined scheduledexecutorservice object to execute the task. The task is executed once per second. The task that can be executed repeatedly must be of the runnable type. Note that we can use timeunit to set the time unit, which is also a new feature of java5.0. The time unit before 5.0 is in microseconds, and can now be accurate to Nai seconds.
* 4: Call the scheduledexecutorservice object to execute the second task. The second task is to cancel the first task in five seconds.
* 5: Close the service.