4

我正在开发一个 Java 调度系统,它根据startDateendDate发生(每小时、每天、每周、每月、星期一等)发送提醒。最初我使用TimerTimerTask类来安排提醒:

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 + period再次发生,而不是startDate + period

有什么想法可以(重新)安排过去startDate的提醒吗?

4

2 回答 2

2

只需快速检查一下日期是否过去,然后创建一个新的临时开始日期时间,它是现在开始时间的增量。

于 2010-07-07T16:45:44.237 回答
0

我通过在启动时运行一次然后在我每天想要的时间运行它来解决它:

// 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
);
于 2018-05-05T16:14:07.867 回答