I want to run some code at the beginning of each minute, my code looks like:
#include <bits/stdc++.h>
int main(){
using namespace std;
using namespace std::chrono_literals;
auto start_ctime = time(NULL)/60*60+60;//beginning second of next minute
auto until= chrono::system_clock::from_time_t(start_ctime);
for(;;until+=60s){
this_thread::sleep_until(until);
auto diff=time(NULL)-start_ctime;
cout<<diff<<endl;
}
}
output:
0
59
120
180
239
300
Seems in some iterations, either
sleep_for
returned before the timepoint specified, which doesn't conform with the requirement of it ornanosleep
(which seems to be called by the implementation).- Or
time
returns a time before the real time
What could happen? I am using g++ 11.2.0 and Ubuntu 22.04