import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ConcurrentStuff { public static void main(String[] args) { System.out.println("begin"); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); System.out.println("scheduling a task to run after 2 seconds"); // Schedule a task to run after a delay of 2 seconds executor.schedule(new MyTask(), 2, TimeUnit.SECONDS); System.out.println("scheduling a task to delay 3 seconds then repeat every 5 seconds"); // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds executor.scheduleAtFixedRate(new MyTask(), 3, 5, TimeUnit.SECONDS); // Wait for scheduled tasks to complete try { System.out.println("sleeping to demo scheduling at work"); Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); System.out.println("end"); } static class MyTask implements Runnable { @Override public void run() { System.out.println("Task executed at: " + new java.util.Date()); } } }
Wednesday, September 18, 2024
Java ScheduledExecutorService
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment