Explain Codes LogoExplain Codes Logo

Run a Java function after a specific number of seconds

java
timer
scheduled-executor-service
java-8
Nikita BarsukovbyNikita Barsukov·Nov 29, 2024
TLDR

To run a Java function after a specified delay, use the ScheduledExecutorService. Here's an example for you to quickly reference:

import java.util.concurrent.*; public class Scheduler { static void delayedFunction() { System.out.println("Delayed function executed with precision."); // Will it blend? That is the question. } public static void main(String[] args) { ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.schedule(Scheduler::delayedFunction, 5, TimeUnit.SECONDS); service.shutdown(); // Sayonara, executor service! } }

After 5 seconds, delayedFunction() executes. Modify the time and delayedFunction() to fit your use case!

Digging deeper: Exploring Timer alternatives

While ScheduledExecutorService is a go-to for precise timing and flexibility, we have other tools, such as java.util.Timer and javax.swing.Timer, to use in different scenarios.

Your Basic Timer: java.util.Timer

import java.util.*; public class TimerExample { Timer timer; public TimerExample(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds * 1000); // Time's ticking away, TikTok stars. } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); // No, this isn't your kitchen timer. timer.cancel(); // Bye, Timer thread! } } public static void main(String args[]) { new TimerExample(5); System.out.println("Task scheduled."); // Mic drop ⬇️ 🎤 } }

Best used for simpler, non-threaded applications.

Precision Geeks: ScheduledExecutorService

ScheduledExecutorService offers more wiggle room with built-in options like scheduleAtFixedRate and scheduleWithFixedDelay for recurring tasks.

service.scheduleAtFixedRate(() -> { /* your code here */ }, 0, 5, TimeUnit.SECONDS); // Recurring nightmares, anyone?

GUI Aficionado: Swing Timers

For GUI applications, javax.swing.Timer is your knight in shining armor. This does require an implementation of an ActionListener for post-delay tasks.

int delay = 5000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { //...The clock strikes, and voila! Your task is done. } }; new Timer(delay, taskPerformer).start();

Make sure to call setRepeats(false) if a one-time grand entrance of your task is what you're going for.

Advanced topics: Staying ahead of the curve

Life's short, Clean up!: Lifecycle management

Managing the lifecycle is crucial to treat your resources like royalty. Cancel scheduled tasks to see cleaner, efficient working with both java.util.Timer and ScheduledExecutorService:

Future<?> future = service.schedule(...); /* Enjoy a snack...🍟🥤 */ future.cancel(false); // Task cancelled, ongoing tasks get to finish their exit speeches.

Break, but gracefully: Handling exceptions

Life throws unexpected curveballs. So does your function handling. Manage unexpected exceptions properly to avoid silent termination of your scheduled task.

Do it with style: User interface updates

On some platforms, keep your UI in the loop using the runOnUiThread() method for UI updates post-delay.

Tips & Tricks: Timing it to perfection

Precision matters in time-sensitive applications. The impact of system load, JVM warm-up can create time warps, affecting the clock.

Specify Time Units: Choosing the right unit

Use the TimeUnit enum to put a stamp on your time units with style:

service.schedule(..., 5, TimeUnit.SECONDS); // Rather than just 5000 milliseconds

Executor exit strategies: Thread pools

Try executor.shutdown() for a graceful exit, or executor.shutdownNow() for an immediate shutdown for matching your applications lifecycle.

Flexible worker configurations: Executor pools

Experiment with Executor factory methods such as newCachedThreadPool (recycles threads!) or newFixedThreadPool (For those who like consistency and control) for varied thread control needs.