Implementing Cron-Based Scheduled Tasks in Spring

Cron Expression Syntax

A cron expression is a string that defines the schedule for task execution. It consists of 6 or 7 fields separated by spaces:

Field Allowed Values Special Characters
Second 0-59 , - * /
Minute 0-59 , - * /
Hour 0-23 , - * /
Day of Month 1-31 , - * / ? L W
Month 1-12 or JAN-DEC , - * /
Day of Week 1-7 or SUN-SAT , - * / ? L #
Year (otpional) 1970-2099 , - * /

Special Characters

Character Meaning Example
* All values * * * * ? - every second
? No specific value 0 0 0 15 * ? - 15th of every month
- Range 0 0 8-18 * * ? - every hour from 8 AM to 6 PM
, List 0 0 8,12,18 * * ? - 8 AM, noon, and 6 PM
/ Increment 0 0 0/4 * * ? - every 4 hours

Common Examples

1 2 3 4 5 ? — 3:02:01 on May 4th every year

23 44 11 22 * ? 2024-2025 — 11:44:23 on the 22nd of every month during 2024-2025

0 * * * * ? — Every minute

0 0 0 * * ? — Every day at midnight

Spring Task Configuration

Spring Boot includes the necessary dependencies through spring-boot-starter, so no additional dependencies are required.

Enabling Scheduled Tasks

Add @EnableScheduling to any configuration class:

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Creating a Scheduled Task

Use @Scheduled with a cron expression to define task execution:

@Component
public class OrderProcessor {
    
    @Scheduled(cron = "0 0 2 * * ?")
    public void processDailyOrders() {
        // Business logic for daily order processing
    }
    
    @Scheduled(cron = "0 */15 * * * ?")
    public void cleanupExpiredSessions() {
        // Cleanup logic every 15 minutes
    }
}

The scheduled method executes automatically according to the specified cron expression. Multiple @Scheduled methods can exist in a single class, each following its own schedule.

Tags: Spring scheduled-tasks cron java

Posted on Fri, 04 Sep 2026 16:44:56 +0000 by austar