Skip to main content

Schedule Tasks with Spring

· One min read
Apache Wangye
Software developer and technical writer

Enable scheduling with @EnableScheduling, then annotate managed bean methods with @Scheduled.

@Component
public class CleanupJob {
@Scheduled(cron = "0 0 2 * * *", zone = "UTC")
public void cleanExpiredData() {
// idempotent cleanup
}
}

fixedRate measures from the previous start, while fixedDelay measures from the previous completion:

@Scheduled(fixedDelayString = "${jobs.delay-ms:60000}")

The default scheduler may execute tasks on one thread. Configure a ThreadPoolTaskScheduler when independent jobs should run concurrently, and define error handling so exceptions are observable.

In a multi-instance deployment, every instance normally runs the same scheduled method. Use a distributed lock, leader election, or an external scheduler to prevent duplicate work. Jobs should be idempotent, bounded by timeouts, monitored, and safe to retry.

Page views: --

Total views -- · Visitors --