简体   繁体   中英

C++ - writing a scheduler with std::difftime - how to check for a time (HH:MM:SS) occurence during the day?

I try to have my program figure if an event is getting reached during the day

for instance, I want to be able to create events at 10:00:00 so that a task gets executed at that moment in the day (only once)

so I have this function that can tell the time has passed, but it will always return true after 10:00 (time parameter)

bool Tools::passedTimeToday(std::time_t time)
{
    auto now = std::chrono::system_clock::now();
    std::time_t _now = std::chrono::system_clock::to_time_t(now);
    if (std::difftime(_now,time)<0)
        return false;
    else
        return true;
}

how do I check the time has passed only once ?

do I use some sort of epsilon around that time ? what value shoud I use for that epsilon ?

    double delta = std::difftime(_now,time);
    if ( (delta<0) && (delta>-epsilon) )
    {
        ...

I mean it could work, but what if my program tests that condition too late (bigger than epsilon) ?

I thought about using a boolean flag instead (bool processed), but then evey time I run the program, it would also run all tasks that happened around that time

any help appreciated

thanks

  1. Create a list with the scheduled tasks and their next run time sorted by the next run time.

  2. When the current time is after the next run time of the first task in the list, remove it from the list, execute the task and then add it back to the list with the run time incremented by a day (or whatever repetition period you need).

  3. Go to step 2 unless the list is empty.

Here is my way of doing it

I only admit tasks within a 5 seconds period

bool Tools::passedTimeToday(std::time_t time)
{
    auto now = std::chrono::system_clock::now();
    std::time_t _now = std::chrono::system_clock::to_time_t(now);
    double delta = std::difftime(_now,time);

    if ( (delta>0) && (delta<5) )
        return true;
    else
        return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM