[英]ScheduledExecutorService.scheduleAtFixedRate And Setting initialDelay To Date In The Past
I'm working on a scheduling system in Java that sends out reminders based on a startDate , endDate and occurrence (hourly, daily, weekly, monthly, Mondays, etc). 我正在使用Java的调度系统,该系统基于startDate , endDate和事件 (每小时,每天,每周,每月,星期一等)发送提醒。 Originally I was using Timer and TimerTask classes to schedule the reminders:
最初,我使用Timer和TimerTask类来安排提醒:
Timer timer = new Timer();
timer.scheduleAtFixedRate(reminder, firstDate, period);
I recently switched to ScheduledExecutorService so I could have more control on cancelling events. 我最近切换到ScheduledExecutorService,因此可以对取消事件进行更多控制。 The ScheduledExecutorService is working well for recurring reminders, except for the one case of rescheduling a reminder with a startDate in the past.
ScheduledExecutorService可以很好地用于重复提醒,但过去的一种情况是使用startDate重新安排提醒。 The scheduleAtFixedRate function only allows you to specify long value for initialDelay , and not an actual Date object:
scheduleAtFixedRate函数仅允许您为initialDelay指定长值,而不是实际的Date对象:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(reminder, initialDelay, period, unit);
This poses a problem, since passing in a negative initialDelay still causes the event to be fired immediately thus causing it to reoccur at now + period , rather than startDate + period . 这带来了一个问题,因为传入负的initialDelay仍然会导致事件立即被触发,从而导致事件在now + period而不是startDate + period再次发生。
Any ideas how I can (re)schedule a reminder with the startDate in the past? 有什么想法可以怎样用startDate来(重新)安排提醒吗?
只需快速检查一下日期是否是过去的日期,然后创建一个新的临时开始日期时间即可,即现在开始的时间增量。
I solved it by running it once on startup and then at the time I wanted every day: 我通过在启动时运行一次然后在每天都想运行的时候解决了它:
// check once initial on startup
doSomething();
// and then once every day at midnight utc
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
LocalDateTime firstRun = LocalDate.now(ZoneOffset.UTC).atStartOfDay().plusDays(1);
Duration durationUntilStart = Duration.between(LocalDateTime.now(ZoneOffset.UTC), firstRun);
scheduler.scheduleAtFixedRate(
() -> doSomething(),
durationUntilStart.getSeconds() + 1,
Duration.ofDays(1).getSeconds(),
TimeUnit.SECONDS
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.