我的C++程序有一个主循环,一直运行直到程序说完了.在主循环中,我希望能够在某些时间间隔内发生某些事情.像这样:
int main()
{
while(true)
{
if(ThirtySecondsHasPassed())
{
doThis();
}
doEverythingElse();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我希望每30秒调用一次doThis(),如果不需要调用,则允许主循环继续并处理其他所有内容.
我怎样才能做到这一点?另请注意,此计划旨在持续运行数天,数周甚至数月.
这是一个更通用的课程,你可以有独立的计时器.
class Timer{
public:
Timer(time_type interval) : interval(interval) {
reset();
}
bool timedOut(){
if(get_current_time() >= deadline){
reset();
return true;
}
else return false;
}
void reset(){
deadline = get_current_time() + interval;
}
private:
time_type deadline;
const time_type interval;
}
Run Code Online (Sandbox Code Playgroud)