Does anyone has any experience with task scheduling in Spring? I understand you can schedule for a fixed time period or interval using annotations https://spring.io/guides/gs/scheduling-tasks/ But I was wondering if anyone knows how to do this using dynamic user input at runtime. For example a user schedules an email to be sent at 5:02pm exactly, is there a way add a new task dynamically using that as a time?
Asked
Active
Viewed 2,152 times
1 Answers
2
- Collect user input and store it in DB as date/time, for example, we can call that value as NEXT_SEND_TIME.
2.Annotate mail sending method with @Scheduled as below, this method will be called automatically( by spring) for every 5 seconds (5000 ms).
3.Get current time and compare it with NEXT_SEND_TIME.
4.If current time is greater than NEXT_SEND_TIME , then trigger email for that user.
@Scheduled(fixedDelay=5000)
public void sendMail() {
// do step 3 & 4 here
}

Sundararaj Govindasamy
- 8,180
- 5
- 44
- 77
-
1Thanks for the reply, I am doing something similar to that at the minute but the issue is it wastes CPU cycles by constantly checking every 5 seconds (maybe an email won't be scheduled to be sent for another 3 hours, yet this will be checking every 5 seconds regardless) It is also inaccurate as the email will never be sent exactly when specified (there'll be a ~5 second window) – stewartie4 Mar 25 '17 at 18:45
-
This is what you are looking for - Spring Scheduler change cron expression dynamically. http://stackoverflow.com/questions/20546403/spring-scheduler-change-cron-expression-dynamically – Sundararaj Govindasamy Mar 31 '17 at 02:53