Category: java
cron job in spring boot
Published on 11 Sep 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:
@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:
@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:
@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:
@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:
// 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:
@Component
public class CertificateScheduler {
@Scheduled(cron = "0 0 8 * * *")
public void sendCertificates() {
System.out.println("Sending
certificates automatically at 8 AM");
}
}