Site icon NgDeveloper

Scheduler in Spring Boot with 3 Simple Steps Example

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.

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:

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

 

Exit mobile version