ScheduledExecutorService.scheduleAtFixedRate并将过去的initialDelay设置为日期 [英] ScheduledExecutorService.scheduleAtFixedRate And Setting initialDelay To Date In The Past

查看:166
本文介绍了ScheduledExecutorService.scheduleAtFixedRate并将过去的initialDelay设置为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java计划系统,该系统基于 startDate endDate 发生(每小时,每天)发出提醒,每周,每月,星期一等).最初,我是使用 Timer TimerTask 类来安排提醒的时间:

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

我最近切换到了 ScheduledExecutorService ,因此我可以对取消事件进行更多控制. ScheduledExecutorService 对于重复提醒非常有效,除了过去使用 startDate 重新安排提醒的一种情况. scheduleAtFixedRate 函数仅允许您为 initialDelay 指定 long 值,而不是实际的 Date 对象:

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

这带来了一个问题,因为传入负的 initialDelay 仍然会导致事件立即被触发,从而导致事件在 now + 期间再次发生,而不是 startDate + 期间.

有什么想法可以让我过去通过 startDate 来(重新)安排提醒时间吗?

解决方案

只需快速检查一下日期是否为过去的日期,然后创建一个新的临时开始日期时间即可,即现在开始的时间增量./p>

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). Originally I was using Timer and TimerTask classes to schedule the reminders:

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

I recently switched to ScheduledExecutorService so I could have more control on cancelling events. The ScheduledExecutorService is working well for recurring reminders, except for the one case of rescheduling a reminder with a startDate in the past. The scheduleAtFixedRate function only allows you to specify long value for initialDelay, and not an actual Date object:

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.

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

解决方案

Just do a quick check to see if the date is in the past, then create a new temporary start datetime that is the increment of the start past now.

这篇关于ScheduledExecutorService.scheduleAtFixedRate并将过去的initialDelay设置为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆