Write Java asynchronous thread which runs code every 10 seconds
- User
Write Java asynchronous thread which runs code every 10 seconds
- Assistant
To implement an asynchronous task in Java that runs code every 10 seconds, you can use the
ScheduledExecutorService. This provides a high-level API for scheduling tasks to run periodically or after a fixed delay. Here's a simple example to demonstrate how you can achieve this:import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledTask { public static void main(String[] args) { // Create a ScheduledExecutorService with a single thread ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // Create a Runnable task to run Runnable task = () -> { System.out.println("Task is running at: " + System.currentTimeMillis()); // Your code here that you want to run every 10 seconds }; // Schedule the task to run every 10 seconds with an initial delay of 0 scheduler.scheduleAtFixedRate(task, 0, 10, TimeUnit.SECONDS); // To keep the program running you would typically have a condition or mechanism to terminate it properly // For this example, we will let it run indefinitely and rely on manual termination (e.g., Ctrl+C) // Uncomment below lines to terminate after a certain time, for example: after 1 minute // scheduler.schedule(() -> scheduler.shutdown(), 1, TimeUnit.MINUTES); } }Explanation:
-
ScheduledExecutorService: This is part of the
java.util.concurrentpackage and is used for scheduling tasks at a fixed rate or with a fixed delay. -
Executors.newScheduledThreadPool(1): This creates a
ScheduledExecutorServicewith a single thread. You can increase the number of threads if needed. -
scheduleAtFixedRate: This method schedules the provided task to run at a regular interval. The first parameter is the task to execute, the second is the initial delay before the task runs for the first time, the third is the period between successive executions, and the last parameter is the time unit for the initial delay and period.
-
CurrentTimeMillis: This is used to print the current time in milliseconds for demonstration purposes.
Note:
-
Ensure that the task you execute inside the
Runnabledoesn't block the thread for longer than your scheduling interval, as this would cause delays in subsequent executions. -
This example is designed for simplicity and demonstration. Depending on your application's requirements, you might need additional error handling, more threads, or shutdown hooks for clean termination.
-