运行在C++应用程序后面的C++计时器

C++ Timer that runs at back of an C++ application

本文关键字:C++ 计时器 应用程序 运行      更新时间:2023-10-16

我有一个在前台运行的C++应用程序。我需要一个与应用程序同时运行的计时器。当计时器达到零时,我需要计时器弹出一个窗口。

我不能使用sleep(),因为who应用程序处于睡眠状态。请就如何做到这一点提供建议。

由于您使用的是C++11,我建议使用thread库。

您可能想要的是std::this_thread::sleep_forstd::this_thread::sleep_until,它们可以在定时器线程的上下文中调用。

像这样的。。。

std::thread timer([]() {
  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "hello, world!" << std::endl;
});
std::cout << "thread begun..." << std::endl;
timer.join();

我建议下载Boost库,然后使用这个关于创建Boost线程的非常简单的教程。

如果您不想花时间下载/安装/配置Boost,请使用Windows线程。(我假设您正在尝试使用Windows上的sleep())。不过,Windows线程比Boost线程更难理解。

在实际的程序中,你会想要包含这样的东西(以Boost为例):

void timer() {
    sleep(x);
    //Whatever code here to make your popup window.
    return NULL;
}
int main() {
    boost::thread prgmTimer(&timer);
    //Regular code here.
    //prgmTimer.join(); //Remove the comment on that command if you want something to
                        //to happen after your timer runs down and only if your
                        //timer runs down. (Ex. the program exits).
    return 0;
}