Hackforge Academy

Category: React • Beginner

Published on 06 Apr 2026

Explanation

Cron is a time-based scheduler used to execute tasks automatically at specific intervals such as every minute, daily at 9 AM, or every Monday. In Spring Boot, cron jobs are implemented using the @Scheduled annotation.

Code Example

@Scheduled(cron = "0 */1 * * * *")
public void runTask() {
    System.out.println("Runs every 1 minute");
}

Explanation

To enable cron scheduling in Spring Boot, you must add @EnableScheduling annotation in the main application class. Without this, scheduled tasks will not execute.

Code Example

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

Explanation

A scheduled task is created inside a Spring component class using @Scheduled annotation with a cron expression that defines execution timing.

Code Example

@Component
public class MyScheduler {

    @Scheduled(cron = "0 */5 * * * *")
    public void executeTask() {
        System.out.println("Runs every 5 
minutes");
    }
}

Explanation

Cron expressions in Spring Boot contain 6 fields: second, minute, hour, day of month, month, and day of week. Example below runs daily at 9 AM.

Code Example

@Scheduled(cron = "0 0 9 * * *")
public void dailyTask() {
    System.out.println("Runs every day
 at 9 AM");
}

Explanation

Instead of hardcoding cron expressions, it is recommended to store them inside application.properties for flexibility and easier updates without modifying source code.

Code Example

// application.properties
scheduler.cron=0 0 10 * * *

// Scheduler class
@Scheduled(cron = "${scheduler.cron}")
public void scheduledTask() {
    System.out.println("Runs daily at 10 AM");
}

Explanation

Cron scheduling is useful for background automation tasks such as sending emails, generating reports, cleaning logs, or notifying students about certificates in training platforms like yours 🎓.

Code Example

@Component
public class CertificateScheduler {

    @Scheduled(cron = "0 0 8 * * *")
    public void sendCertificates() {
        System.out.println("Sending 
certificates automatically at 8 AM");
    }
}

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.