From 0dd9df49d7833a2d2119e4a6ff8282df58b12d5d Mon Sep 17 00:00:00 2001 From: progheal Date: Sat, 27 Aug 2022 15:06:52 +0800 Subject: [PATCH] Fix task may appear to be triggered more than 1 second late (#27) * Fix task may appear to be triggered more than 1 second late * Add comment Co-authored-by: Per Malmberg --- libcron/src/CronSchedule.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/libcron/src/CronSchedule.cpp b/libcron/src/CronSchedule.cpp index af00b3b..9d9a456 100644 --- a/libcron/src/CronSchedule.cpp +++ b/libcron/src/CronSchedule.cpp @@ -81,6 +81,16 @@ namespace libcron } } + // Discard fraction seconds in the calculated schedule time + // that may leftover from the argument `from`, which in turn comes from `now()`. + // Fraction seconds will potentially make the task be triggered more than 1 second late + // if the `tick()` within the same second is earlier than schedule time, + // in that the task will not trigger until the next `tick()` next second. + // By discarding fraction seconds in the scheduled time, + // the `tick()` within the same second will never be earlier than schedule time, + // and the task will trigger in that `tick()`. + curr -= curr.time_since_epoch() % seconds{1}; + return std::make_tuple(max_iterations > 0, curr); } } \ No newline at end of file