Creating Timer Tasks
Task Creation Strategies
Defining TimerTask
In Java, creating timer tasks involves extending the TimerTask
abstract class or using anonymous inner classes. There are multiple approaches to implement timer tasks:
graph TD
A[TimerTask Creation] --> B[Extend TimerTask Class]
A --> C[Anonymous Inner Class]
A --> D[Lambda Expression]
Basic TimerTask Implementation
Method 1: Extending TimerTask Class
import java.util.Timer;
import java.util.TimerTask;
public class CustomTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("Custom task executed");
}
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new CustomTimerTask(), 1000);
}
}
Method 2: Anonymous Inner Class
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Anonymous task executed");
}
}, 1000);
Method 3: Lambda Expression (Java 8+)
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Lambda-style task");
}
}, 1000);
Scheduling Task Types
Task Type |
Method |
Description |
One-time Delay |
schedule(task, delay) |
Executes task once after specified delay |
One-time Specific Time |
schedule(task, date) |
Executes task at specific date/time |
Periodic Fixed Rate |
scheduleAtFixedRate(task, delay, period) |
Repeats task at fixed interval |
Periodic Fixed Delay |
scheduleAtFixedDelay(task, delay, period) |
Repeats task with fixed delay between executions |
Advanced Task Scheduling Example
import java.util.Timer;
import java.util.TimerTask;
public class AdvancedTimerDemo {
public static void main(String[] args) {
Timer timer = new Timer();
// Periodic task with fixed rate
timer.scheduleAtFixedRate(new TimerTask() {
private int count = 0;
@Override
public void run() {
count++;
System.out.println("Periodic task: " + count);
// Cancel after 5 executions
if (count >= 5) {
cancel();
}
}
}, 1000, 2000); // Initial delay: 1 second, Period: 2 seconds
}
}
Task Cancellation and Management
Cancelling Tasks
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Cancellable task");
}
};
timer.schedule(task, 1000);
task.cancel(); // Cancels the specific task
Best Practices
- Avoid long-running tasks in TimerTask
- Handle exceptions within the
run()
method
- Use
Timer.cancel()
to stop all scheduled tasks
- Consider
ScheduledExecutorService
for complex scheduling
At LabEx, we recommend understanding these task creation techniques to build robust scheduling mechanisms in your Java applications.