package com.example.lambda;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorExample {

	public static void main(String[] args) {
		ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
		
		// define the task (runnable or callable)
		DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		Runnable task = () -> System.out.println("Scheduled task executed at " 
								+ LocalDateTime.now().format(format));
		
		// schedule task to be executed once after 5 seconds
		System.out.println("Run the task after 5 seconds...");
		scheduler.schedule(task, 5, TimeUnit.SECONDS);
		
		// schedule the task to run periodically every 3 seconds with 
		// an initial delay of 1 second
		System.out.println("Run the task periodically...");
		scheduler.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
	}

}
