ScheduledExecutorService.scheduleAtFixedRate And setting initialDelay To Date In The Past

I am working on a Java planning system that sends reminders based on startDate, endDate and occurrences (hourly, daily, weekly, monthly, Mondays, etc.). I originally used Timer and TimerTask to schedule reminders:

Timer timer = new Timer();
timer.scheduleAtFixedRate(reminder, firstDate, period);

I recently switched to ScheduledExecutorService so that I can have more control over event cancellation. ScheduledExecutorService works well for recurring reminders, with the exception of one case of redirecting a reminder with startDate in the past. The scheduleAtFixedRate function allows you to specify a long value for initialDelay, rather than the actual Date object:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(reminder, initialDelay, period, unit);

This creates a problem, since passing a negative initialDelay still causes the event to fire immediately, which causes it to repeat at the moment + period, rather than startDate + period.

Any ideas how I can (re) schedule a reminder with startDate in the past?

+3
source share
1 answer

Just do a quick check to see if the date was in the past, and then create a new datetime beginning time, which is an increment of the beginning in the past.

+2
source

Source: https://habr.com/ru/post/1753558/


All Articles