Bosma / Scheduler

Modern C++ Scheduling Library
MIT License
272 stars 74 forks source link

Time Drift using every #25

Open johnhlaferriere opened 2 years ago

johnhlaferriere commented 2 years ago

I am using an every call to run a function once a minute. this is to happen exactly on the minute and zero second. It starts out working perfectly, however over time, the execution starts to drift, and executes a second, then 2, then 3... later. Is there something that can be done to improve the precision of execution ?

johnhlaferriere commented 2 years ago

Looks like I may have solved my own issue.

in schedule,h I modified the EVERY class to:

`class EveryTask : public Task {

public:
    EveryTask(Clock::duration time, std::function<void()> &&f, bool interval = false) :
            Task(std::move(f), true, interval), time(time) {}

    Clock::time_point get_new_time() const override {
      return std::chrono::time_point_cast<Sec>(Clock::now()) + time;
    };
    Clock::duration time;

};

`

adding the following usings to the top of the file: using Sec = std::chrono::seconds; using Ms = std::chrono::seconds;

This change truncates the current system time to seconds keeping the clock drift from happening. This way the scheduler executes on the second.. This may not be ideal for all. I may try adding a precision argument to allow control the level of this truncation