'Spring Boot : execute a job at a particular Date entered by the user
Im trying to manage scheduled tasks using spring boot. I want to execute my job only one time at a particular date ( specified by the user ). Here is my Job :
@Component
public class JobScheduler{
@Autowired
JobController controller;
// Retrieving the Date entered by the user
controller.getDateForExecution(); // 2016/05/24 10:00 for example
@Scheduled(???)
public void performJob() throws Exception {
controller.doSomething();
}
There are multiple options for Scheduled annotation such as fixedDelay, fixedRate, initialDelay, cron ... but none of these can accept a Date. So, how can i execute my method at the specified Date dynamically ( ie depending on the Date insered ) ?
Ps : The method can be executed more than once if the user enter two or more Dates ..
Solution 1:[1]
Spring has the TaskScheduler abstraction that you can use: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler
It has a method to schedule execution of a Runnable
at a certain Date
:
ScheduledFuture schedule(Runnable task, Date startTime);
A little off-topic maybe: If JobController
is a Spring Controller
(or RestController
), I would not autowire it into the JobScheduler
. I would inverse it and inject the JobScheduler
into the JobController
.
Solution 2:[2]
Ok I know this is a very old questions but for future references, here's the answer:
You can use cron property, which gives much more control over the scheduling of a task. It lets us define the seconds, minutes ,and hours the task runs at but can go even further and specify even the years that a task will run in.
Below is a breakdown of the components that build a cron expression.
Seconds can have values 0-59 or the special characters , - * / .
Minutes can have values 0-59 or the special characters , - * / .
Hours can have values 0-59 or the special characters , - * / .
Day of month can have values 1-31 or the special characters , - * ? / L W C .
Month can have values 1-12, JAN-DEC or the special characters , - * / .
Day of week can have values 1-7, SUN-SAT or the special characters , - * ? / L C # .
Year can be empty, have values 1970-2099 or the special characters , - * / .
Just for some extra clarity, I have combined the breakdown into an expression consisting of the field labels.
@Scheduled(cron = "[Seconds] [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]")
For more you can follow this article: https://dzone.com/articles/running-on-time-with-springs-scheduled-tasks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wim Deblauwe |
Solution 2 | Shïvà Tömàr |