Java timing task
Delayed function execution
Java Timer
Scheduled task
Java threads

Run a java function after a specific number of seconds

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java provides a variety of ways to execute a function after a specific period of time. Whether you are building a simple application or a complex system, understanding how to schedule tasks is an essential skill. In this article, we’ll explore several techniques for achieving this, complete with technical explanations and examples.

Utilizing java.util.Timer

java.util.Timer and java.util.TimerTask provide a straightforward mechanism for scheduling tasks. You can use these classes to execute a task once after a delay or to execute repeatedly at a fixed rate.

Example

java
1import java.util.Timer;
2import java.util.TimerTask;
3
4public class TimerExample {
5    public static void main(String[] args) {
6        Timer timer = new Timer();
7        TimerTask task = new TimerTask() {
8            @Override
9            public void run() {
10                System.out.println("Task executed!");
11                timer.cancel(); // To stop the timer once the task is executed
12            }
13        };
14        long delay = 5000; // 5000 milliseconds = 5 seconds
15        timer.schedule(task, delay);
16    }
17}

In the example above, a TimerTask is scheduled to run after a 5-second delay.

Key Points

  • Timer and TimerTask: Facilitates scheduling but does not support complex models.
  • Single-threaded execution: A single timer uses only one thread. If a task takes longer to execute, subsequent tasks may be delayed.

Employing ScheduledExecutorService

ScheduledExecutorService is a more flexible approach, especially useful when you need to handle concurrent tasks across multiple threads.

Example

java
1import java.util.concurrent.Executors;
2import java.util.concurrent.ScheduledExecutorService;
3import java.util.concurrent.TimeUnit;
4
5public class ScheduledExecutorServiceExample {
6    public static void main(String[] args) {
7        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
8
9        Runnable task = () -> System.out.println("Task executed!");
10
11        long delay = 5; // 5 seconds
12        scheduler.schedule(task, delay, TimeUnit.SECONDS);
13        
14        scheduler.shutdown();
15    }
16}
  • This code snippet creates a task that runs once after a 5-second delay.
  • We employ shutdown() to stop the executor after task execution.

Advantages

  • Thread management: Allows the use of a thread pool.
  • Advanced scheduling: Provides more advanced scheduling capabilities compared to java.util.Timer.

Using java.lang.Thread.sleep

For simpler applications, you might use Thread.sleep, although it is not a scheduling tool per se.

Example

java
1public class SleepExample {
2    public static void main(String[] args) {
3        Runnable task = () -> System.out.println("Task executed!");
4        
5        try {
6            Thread.sleep(5000); // Sleep for 5 seconds
7            task.run();
8        } catch (InterruptedException e) {
9            Thread.currentThread().interrupt();
10        }
11    }
12}

Drawbacks

  • Blocking method: Pauses the executing thread, which can be inefficient.
  • No task scheduling: Lacks the sophistication of scheduling tools.

Summary Table

FeatureTimer and TimerTaskScheduledExecutorServiceThread.sleep
Thread ControlSingle-thread Timing issuesMultiple threads Better scalabilityBlocks executing thread
Rescheduling & RepeatingLimited to manual re-scheduling Limited flexibilitySupports fixed-rate and delay Advanced featuresManual rescheduling only
Use CaseSimple periodic/single delaysConcurrent task execution Complex schedulingSimple, non-concurrent tasks
Error HandlingMinimal error handlingMore structured error managementMinimal error handling

Conclusion

The choice of method to execute functions after a delay depends on the use case and complexity of your application. For basic needs, Timer and TimerTask could suffice. However, for concurrent and complex scheduling, ScheduledExecutorService is generally the better choice due to its flexibility and improved thread management. Thread.sleep, while easy to implement, should be reserved for very simple operations due to its blocking nature.

Consider threading implications, error handling, and task complexity when deciding which approach to implement for delayed task execution in Java.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.