You can schedule a task using ScheduledExecutorService interface,
You can get it from static factory methods of the Executors class.
Or You can use the its concrete implementation 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 which is task1 after a certain delay (10 seconds), use the following code
sexec.schedule(task1, 10, TimeUnit.SECONDS);
To schedule task2 after 10 seconds, and repeat after 25 seconds, use
sexec.scheduleAtFixedRate(task2, 10, 25, TimeUnit.SECONDS);
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);
You can schedule a task to execute at an absolute time using the following code.
LocalDateTime scheduledDateTime = a local future time // 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);
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.
The following code demonstrates how to schedule a task.
The second task has been scheduled to run repeatedly.
It makes the main thread sleep for 60 seconds before you shut down the executor.
import java.time.LocalDateTime; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; class MyTask implements Runnable { private int taskId; public MyTask(int taskId) { this.taskId = taskId; }//w w w . j a v a 2 s . co m public void run() { LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Task #" + this.taskId + " ran at " + currentDateTime); } } public class Main { public static void main(String[] args) { // Get an executor with 3 threads ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3); // Task #1 and Task #2 MyTask task1 = new MyTask(1); MyTask task2 = new MyTask(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); try { TimeUnit.SECONDS.sleep(60); } catch (InterruptedException e) { e.printStackTrace(); } // Shut down the executor sexec.shutdown(); } }