package com.example.demo.scheduled;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class ScheduledTasks {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
private final UserService userService;
public ScheduledTasks(UserService userService) {
this.userService = userService;
}
// Run every 5 seconds
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
logger.info("Current time: {}", LocalDateTime.now().format(formatter));
}
// Wait 3 seconds after previous execution completes
@Scheduled(fixedDelay = 3000)
public void processWithDelay() {
logger.info("Processing with fixed delay");
}
// Run with initial delay
@Scheduled(initialDelay = 10000, fixedRate = 60000)
public void taskWithInitialDelay() {
logger.info("Task with initial delay executed");
}
// Cron: Every day at 2 AM
@Scheduled(cron = "0 0 2 * * ?")
public void performNightlyCleanup() {
logger.info("Starting nightly cleanup");
// Clean up old data
}
// Cron: Every Monday at 9 AM
@Scheduled(cron = "0 0 9 * * MON")
public void generateWeeklyReport() {
logger.info("Generating weekly report");
}
// Cron: Every 15 minutes
@Scheduled(cron = "0 */15 * * * ?")
public void refreshCache() {
logger.info("Refreshing cache");
userService.clearCache();
}
// Cron: First day of every month at midnight
@Scheduled(cron = "0 0 0 1 * ?")
public void monthlyTask() {
logger.info("Monthly task executed");
}
// Only in production profile
@Scheduled(cron = "0 0 * * * ?")
@org.springframework.context.annotation.Profile("prod")
public void prodOnlyTask() {
logger.info("Production-only hourly task");
}
}
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling
@EnableAsync
public class SchedulingConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
scheduler.setThreadNamePrefix("scheduled-task-");
scheduler.initialize();
taskRegistrar.setTaskScheduler(scheduler);
}
}
Spring's @Scheduled annotation enables method execution on fixed intervals or cron expressions. @EnableScheduling activates scheduling infrastructure. Fixed delay waits after completion, fixed rate executes at intervals regardless of duration. Cron expressions provide sophisticated scheduling—specific times, days, months. Initial delay postpones first execution. Async execution with @Async prevents blocking. Multiple schedulers use @Scheduled on separate methods. Scheduled tasks handle maintenance—data cleanup, report generation, cache warming. Dynamic scheduling uses TaskScheduler programmatically. Conditional scheduling with Spring Profiles enables/disables tasks per environment. Proper error handling prevents task failures from stopping future executions. Scheduled tasks are essential for batch processing and periodic operations.