Java Reference
In-Depth Information
Scheduling a Task
The executor framework lets you schedule a task that will run in future. You can run a task to execute after a given
delay or periodically. Scheduling a task is done using an object of the ScheduledExecutorService interface,
which you can get using one of the static factory methods of the Executors class. You can also use the concrete
implementation of this interface, which is the ScheduledThreadPoolExecutor class. To get an object of the
ScheduledExecutorService interface, use the following snippet of code:
// Get scheduled executor service with 3 threads
ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3);
To schedule a task (say task1 ) after a certain delay (say 10 seconds), use
sexec.schedule(task1, 10, TimeUnit.SECONDS);
To schedule a task (say task2 ) after a certain delay (say 10 seconds), and repeat after a certain period
(say 25 seconds), use
sexec.scheduleAtFixedRate(task2, 10, 25, TimeUnit.SECONDS);
After a 10 second delay, task2 will execute for the first time. Subsequently, it will keep executing after
10 + 25 seconds, 10 + 2 * 25 seconds, 10 + 3 * 25 seconds, and so on.
You can also schedule a task with a set delay period between the end of an execution and the start of the next
execution. To schedule task3 , for the first time after 40 seconds, and every 60 seconds after every execution finishes, use
sexec.scheduleWithFixedDelay(task3, 40, 60, TimeUnit.SECONDS);
The ScheduledExecutorService interface does not provide a method to schedule a task using an absolute
time. However, you can schedule a task to execute at an absolute time using the following technique. Suppose
scheduledDateTime is the date and time at which you want to execute the task.
import java.time.LocalDateTime;
import static java.time.temporal.ChronoUnit.SECONDS;
import java.util.concurrent.TimeUnit;
...
LocalDateTime scheduledDateTime = get the scheduled date and time for the task...
// Compute the delay from the time you schedule the task
long delay = SECONDS.between(LocalDateTime.now(), scheduledDateTime);
// Schedule the task
sexec.schedule(task, delay, TimeUnit.MILLISECONDS);
the submit() method of ExecutorService submits the task for immediate execution. You can submit a task
for immediate execution using ScheduledExecutorService.schedule() method by specifying an initial delay of zero.
a negative initial delay schedules a task for immediate execution.
Tip
 
 
Search WWH ::




Custom Search