Java Reference
In-Depth Information
Listing 6-51 contains the code for a Runnable task. It simply prints the date and time when it is run. Listing 6-52
demonstrates how to schedule a task. The second task has been scheduled to run repeatedly. To let it run for a few
times, make the main thread sleep for 60 seconds before you shut down the executor. Shutting down an executor
discards any pending tasks. A good way to stop a scheduled task that repeats is to cancel it after a certain delay using
another scheduled task.
Listing 6-51. A Scheduled Task
// ScheduledTask.java
package com.jdojo.threads;
import java.time.LocalDateTime;
public class ScheduledTask implements Runnable {
private int taskId;
public ScheduledTask(int taskId) {
this.taskId = taskId;
}
public void run() {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Task #" + this.taskId + " ran at " + currentDateTime);
}
}
Listing 6-52. A Class to Test Scheduled Task Executions Using the Executor Framework
// ScheduledTaskTest.java
package com.jdojo.threads;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskTest {
public static void main(String[] args) {
// Get an executor with 3 threads
ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3);
// Task #1 and Task #2
ScheduledTask task1 = new ScheduledTask(1);
ScheduledTask task2 = new ScheduledTask(2);
// Task #1 will run after 2 seconds
sexec.schedule(task1, 2, TimeUnit.SECONDS);
// Task #2 runs after 5 seconds delay and keep running every 10 seconds
sexec.scheduleAtFixedRate(task2, 5, 10, TimeUnit.SECONDS);
Search WWH ::




Custom Search