Scheduler in Spring Boot with 3 Simple Steps Example:
Scheduler in spring boot became very simple and any one create a Cron job or scheduler in spring boot with just 3 steps.
Table of Contents
Step 1: Enable spring boot for schedules
Add @EnableScheduling to your spring boot main class.
@SpringBootApplication @EnableScheduling public class SpringBootStarter{ public static void main(String[] args) { SpringApplication.run(SpringBootStarter.class, args); } }
Step 2: Create a cron job component:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class CronJobSchedules { private static final Logger log = LoggerFactory.getLogger(CronJobSchedules.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); // This runs every 60 seconds @Scheduled(cron = "*/60 * * * * *") public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); System.out.println("The time is now {}"+dateFormat.format(new Date())); } }
Cron Job Configuration Samples:
- “*/10 * * * * *” = every ten seconds.
- “0 0 8-10 * * *” = 8, 9 and 10 o’clock of every day.
- “0 0 6,19 * * *” = 6:00 AM and 7:00 PM every day.
- “0 0/30 8-10 * * *” = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
- “0 0 9-17 * * MON-FRI” = on the hour nine-to-five weekdays
- “0 0 0 25 12 ?” = every Christmas Day at midnight
- “0 48/5 * * * *” = every 5 minutes starts from 48th min of every hour.
More details on the spring scheduling, have a quick look at spring documentation.
More details on the cron timing, have a look at spring cron scheduling.
Fantastic snippet from stackoverflow for easy understanding:
Step 3: Annotate reportCurrentTime() with @Scheduled
// This runs every 60 seconds @Scheduled(cron = "*/60 * * * * *") public void reportCurrentTime() {
Now Run and verify the schedules
Output:
2017-10-01 23:15:00.003 INFO 6316 --- [pool-2-thread-1] com.couponzcorner.cron.CronJobSchedules : The time is now 23:15:00 The time is now {}23:15:00 2017-10-01 23:16:00.004 INFO 6316 --- [pool-2-thread-1] com.couponzcorner.cron.CronJobSchedules : The time is now 23:16:00 The time is now {}23:16:00 2017-10-01 23:17:00.002 INFO 6316 --- [pool-2-thread-1] com.couponzcorner.cron.CronJobSchedules : The time is now 23:17:00 The time is now {}23:17:00 2017-10-01 23:18:00.002 INFO 6316 --- [pool-2-thread-1] com.couponzcorner.cron.CronJobSchedules : The time is now 23:18:00 The time is now {}23:18:00 2017-10-01 23:19:00.004 INFO 6316 --- [pool-2-thread-1] com.couponzcorner.cron.CronJobSchedules : The time is now 23:19:00 The time is now {}23:19:00