Mastering Scheduled Tasks in Spring Boot: Timer, Executor, Spring Task, and Quartz
This guide compares four Java scheduling options—Timer, ScheduledExecutorService, Spring Task, and Quartz—showing how to implement each in Spring Boot, configure cron expressions, enable async execution, and choose the right tool for your needs.
Spring Boot offers multiple ways to schedule recurring tasks, each with its own characteristics and use cases.
Timer
Uses the built‑in java.util.Timer and TimerTask. Simple to set up but cannot schedule tasks at a specific time; mainly useful for fixed‑rate execution.
public class TestTimer {
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("task run:" + new Date());
}
};
Timer timer = new Timer();
// start after 10 ms, repeat every 3000 ms
timer.schedule(timerTask, 10, 3000);
}
}ScheduledExecutorService
JDK‑provided thread‑pool‑based scheduler. Each task runs in its own thread, allowing concurrent execution.
public class TestScheduledExecutorService {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(() -> System.out.println("task ScheduledExecutorService " + new Date()),
0, 3, TimeUnit.SECONDS);
}
}Spring Task (Annotation‑Based Scheduling)
Spring 3.0+ provides a lightweight alternative to Quartz. Add the required dependencies, enable scheduling with @EnableScheduling, and annotate methods with @Scheduled using cron, fixedRate, or fixedDelay.
@Slf4j
@Component
public class ScheduledService {
@Scheduled(cron = "0/5 * * * * *")
public void scheduled(){
log.info("=====>>>>>using cron {}", System.currentTimeMillis());
}
@Scheduled(fixedRate = 5000)
public void scheduled1(){
log.info("=====>>>>>using fixedRate {}", System.currentTimeMillis());
}
@Scheduled(fixedDelay = 5000)
public void scheduled2(){
log.info("=====>>>>>fixedDelay {}", System.currentTimeMillis());
}
}Enable with @EnableScheduling on the main application class.
Async Execution for Parallel Tasks
Define a configuration class to create a custom ThreadPoolTaskExecutor and annotate task methods with @Async so each scheduled job runs in a separate thread.
@Configuration
@EnableAsync
public class AsyncConfig {
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean
public Executor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}Cron Expression Details
A cron expression consists of at least six space‑separated fields (seconds, minutes, hours, day‑of‑month, month, day‑of‑week, optional year). Each field can contain a single value, a range, an interval (e.g., 0/15), a list, or a wildcard *. Special characters include ? (no specific value), L (last), W (nearest weekday), # (nth weekday), and C (calendar).
Examples: Every 5 seconds: */5 * ? Every minute at 10 am, 2 pm, and 4 pm: 0 0 10,14,16 ? Every weekday at 10:15 am: 0 15 10 ? * MON-FRI Last Friday of each month at 10:15 am: 0 15 10 ? * 6L
Integrating Quartz
For more complex scheduling, Quartz can be added. Spring Boot 2.0+ already includes spring-boot-starter-quartz. Define a job class extending QuartzJobBean and a configuration class that creates a JobDetail and a Trigger.
public class TestQuartz extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("quartz task " + new Date());
}
}
@Configuration
public class QuartzConfig {
@Bean
public JobDetail testQuartzDetail(){
return JobBuilder.newJob(TestQuartz.class)
.withIdentity("testQuartz")
.storeDurably()
.build();
}
@Bean
public Trigger testQuartzTrigger(){
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever();
return TriggerBuilder.newTrigger()
.forJob(testQuartzDetail())
.withIdentity("testQuartz")
.withSchedule(scheduleBuilder)
.build();
}
}Start the Spring Boot application; the chosen scheduling method will execute according to its configuration.
Overall, Spring Task annotation is the simplest for most cases, while Quartz offers advanced features for complex schedules. Choose based on task complexity, concurrency needs, and required timing precision.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
