TimerTask is a built-in Java class used to schedule tasks for future execution in a background thread. It is part of the java.util package and provides a lightweight way to handle repetitive or delayed operations without full framework overhead. Core Concepts
Timer: The coordinator thread that schedules and runs tasks.
TimerTask: The actual work to be done, which implements the Runnable interface.
Single-Threaded: A single background thread executes all tasks sequentially. Implementation Steps
Extend TimerTask: Define your background logic inside the run() method.
Instantiate Timer: Create a controller object to manage execution.
Schedule Execution: Pass your task and timing parameters to the timer. Code Example
import java.util.Timer; import java.util.TimerTask; public class BackgroundService { public static void main(String[] args) { Timer timer = new Timer(true); // true makes it a daemon thread TimerTask cleanupTask = new TimerTask() { @Override public void run() { System.out.println(“Cleaning temporary files…”); } }; // Run after 1 second delay, then repeat every 5 seconds timer.scheduleAtFixedRate(cleanupTask, 1000, 5000); } } Use code with caution. Scheduling Methods
schedule(): Schedules tasks with a fixed delay between execution starts. Delays accumulate if a task runs late.
scheduleAtFixedRate(): Schedules tasks with a fixed rate. Ideal for activities that must remain synchronized. Major Limitations
Thread Blockage: If one task takes too long, it delays all subsequent tasks.
Runtime Exceptions: If a task throws an uncaught exception, the entire Timer thread dies.
No Thread Pooling: It cannot utilize multiple CPU cores for parallel task execution. Modern Alternatives
For robust production systems, Java’s ScheduledExecutorService is preferred. It uses a thread pool, handles exceptions gracefully, and supports parallel execution.
To help tailor this, let me know if you want to see the ScheduledExecutorService equivalent, need help integrating this into an Android/Spring app, or want to troubleshoot a specific threading issue.
Leave a Reply