Scheduler is used to schedule a thread or task to execute at a certain period of time or periodically at a fixed interval. Scheduling tasks in your Spring applications can be an effective way to automate processes, perform maintenance, and enhance your application’s functionality. Spring’s Task Scheduler provides a convenient and powerful mechanism for scheduling tasks.
Task Scheduling using @Scheduled Annotation:
The simplest way to schedule tasks in Spring is by using the @Scheduled annotation. This annotation can be applied to any method, which will then be executed according to the specified schedule.
The simple rules that we need to follow to annotate a method with @Scheduled are:
The annotated method must not accept arguments. It will typically have a void return type; if not, the returned value will be ignored when called through the scheduler.
Annotation that marks a method to be scheduled. For periodic tasks, exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified, and additionally an optional initialDelay(). For a one-time task, it is sufficient to just specify an initialDelay().
Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. This can be done manually or, more conveniently, through the <task:annotation-driven/> XML element or @EnableScheduling annotation.
Properties:
fixedRate
The fixedRate property runs the scheduled task at every n millisecond. It doesn’t check for any previous executions of the task.This is useful when all executions of the task are independent. If we don’t expect to exceed the size of the memory and the thread pool, fixedRate should be quite handy. Example
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
System.out.println(
"Fixed rate task - " + System.currentTimeMillis() / 1000);
}
fixedDelay
cron expression
Conclusion
we can use the @Scheduled annotation to schedule a task automatically using given attriutes.For example, we can use the scheduler to refresh the webpage for live score of cricket match after certain time to get the updated score and show it on the page. we also can use TaskScheduler interface which provide more control over task scheduling.
Comments