javabeginner
Spring Boot — Scheduled Tasks and Cron
Schedule background tasks with @Scheduled: fixed rate, fixed delay, cron expressions, and async tasks.
javaPress ⌘/Ctrl + Shift + C to copy
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling
public class ScheduledTasks {
// Run every 30 seconds
@Scheduled(fixedRate = 30000)
public void heartbeat() {
System.out.println("Heartbeat: " + LocalDateTime.now());
}
// Run 10 seconds after last execution completes
@Scheduled(fixedDelay = 10000, initialDelay = 5000)
public void pollQueue() {
System.out.println("Polling message queue...");
}
// Cron: every weekday at 8 AM
@Scheduled(cron = "0 0 8 * * MON-FRI")
public void morningReport() {
System.out.println("Generating morning report...");
}
// Cron: every 15 minutes
@Scheduled(cron = "0 */15 * * * *")
public void syncData() {
System.out.println("Syncing data...");
}
// Cron from config: @Scheduled(cron = "${app.cleanup.cron}")
@Scheduled(cron = "0 0 2 * * *") // 2 AM daily
public void cleanupExpired() {
System.out.println("Cleaning up expired sessions...");
}
}
// Async scheduled tasks
@Configuration
@EnableAsync
public class AsyncConfig {
// @Async methods will run in a separate thread
}
@Component
class AsyncJobs {
@Async
@Scheduled(fixedRate = 60000)
public void heavyJob() {
// Runs without blocking the scheduler thread
System.out.println("Heavy job on: " + Thread.currentThread().getName());
}
}Sponsored
Railway
Use Cases
- Background job scheduling in Spring Boot
- Periodic data cleanup and maintenance tasks
- Cron-based report generation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Node.js Cron Job Scheduler
Schedule recurring tasks with node-cron using crontab syntax and timezone support.
Best for: Database cleanup tasks
#cron#scheduler
bashbeginner
Linux Cron Job Setup Examples
Common crontab entries for database backups, log cleanup, health checks, and certificate renewal.
Best for: Automated database backups
#cron#linux
javaintermediate
Spring Boot REST Controller with CRUD
Create a complete REST API with Spring Boot: GET, POST, PUT, DELETE with validation and error handling.
Best for: Building RESTful APIs with Spring Boot
#spring-boot#rest-api
javaintermediate
Spring Boot Global Exception Handler
Centralized error handling with @ControllerAdvice for validation errors, 404s, and custom exceptions.
Best for: Consistent error responses across all endpoints
#spring-boot#error-handling