Skip to content

Execute timer in sync with system clock #2927

Closed Answered by mikee47
mashupmark asked this question in Q&A
Discussion options

You must be logged in to vote

It's risky checking the clock since we cannot guarantee the time is monotonic: NTP updates may cause forward or backward jumps. It's also not efficient using DateTime like this.

I'd recommend just using a Timer configured to fire after the desired interval. Something like this:

const unsigned EVENT_INTERVAL_SECS = 60 * 5;
Timer actionTimer;
time_t nextEventTime;

void scheduleNextEvent();

void handleEvent()
{
    time_t now = SystemClock.now(eTZ_UTC);
    scheduleNextEvent();
}

void scheduleNextEvent()
{
    // Base next event on current time to compensate for clock drift
    time_t now = SystemClock.now(eTZ_UTC);
    unsigned secondsSinceLastEvent = now % EVENT_INTERVAL_SECS;
    unsig…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by slaff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants