SpringBoot – @Scheduler Annotation with Examples
In our applications we might need certain logic or method that needs to be executed at certain intervals. For ex: We might require a method to be executed every 15 min.
In SpringBoot we have an annotation to achieve this, @Scheduled annotation. From package – org.springframework.scheduling.annotation.Scheduled.
@Scheduled types,
- initialDelay
- fixedRate
- fixedDelay
- fixedDelayString
- cron
initialDelay:
- The milliseconds delay before the execution of fixedRate or fixedDelay
fixedRate:
- Invocation with specific period of time
fixedDelay:
- Fixed period between the last invocation and the next invocation
fixedDelayString:
- Same as fixedDelay but this accepts string parameter
- Example: @Scheduled(fixedDelayString = “5000”)
Now for example, if we pass incorrect number as string to fixedDelayString what will happen?
Let us pass this,
@Scheduled(fixedDelayString = “5000r“)
When we try to run this, we will get an exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘myApplication’: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method ‘ScheduledFixedRate’: Invalid fixedDelayString value “5000r” – cannot parse into integer
Cron:
- A cron-like expression which has 6 arguments – Minutes, Hour, Date, Month, Week and Year
- It looks like @Scheduled(cron = “* * * * * *”)
Now let us see an detailed example,
@SpringBootApplication @EnableScheduling public class MyApplication { public static void main(String[] args) throws Exception { SpringApplication.run(MyApplication.class, args); } @Scheduled(fixedDelayString = "5000") public void ScheduledFixedRate(){ Calendar cal = Calendar.getInstance(); System.out.println("Scheduler with FixedRate: "+cal.getTime()); } @Scheduled(fixedDelay = 7000) public void ScheduledFixedDelay(){ Calendar cal = Calendar.getInstance(); System.out.println("Scheduler with FixedDelay: "+cal.getTime()); } @Scheduled(cron = "10 02 21 * * *") public void ScheduledCron(){ Calendar cal = Calendar.getInstance(); System.out.println("Cron Job: "+cal.getTime()); } }
In the above example we have scheduled a cron,
@Scheduled(cron = “10 02 21 * * *”) – This will execute exactly on 21:02:10 – 21 hours, 02 minutes 10 seconds
When the above code is executed,