javabeginner

Spring Boot — Scheduled Tasks and Cron

Schedule background tasks with @Scheduled: fixed rate, fixed delay, cron expressions, and async tasks.

java
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.