C++ 如何每 x 秒调用一次函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15683221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:39:05  来源:igfitidea点击:

How to call a function every x seconds

c++windows

提问by user2219913

I want to write a program to simulate a cafeteria in which a customer enters the cafeteria every 10 ~ 50 seconds. So I wanted a function to be called every 10~50 seconds for displaying the menu card which is present in the function to be called

我想编写一个程序来模拟一个食堂,其中客户每 10~50 秒进入食堂。所以我希望每 10~50 秒调用一个函数来显示要调用的函数中存在的菜单卡

回答by DevSolar

The Boostlibrary provides for this in Boost.Asio, and explicitly covers this in its tutorials:

升压库提供了这Boost.Asio的,并明确包括这在其教程:

If you didn't find the Boost library when searching the web for C++, your google-fu is weak. ;-)

如果您在网上搜索 C++ 时没有找到 Boost 库,则您的 google-fu 很弱。;-)

回答by Some programmer dude

In your main-loop, get the time and compare it to the last time you called the function (initialized to "now" when declaring it). If it's larger than your interval then call your function and set the "last-time-called" variable to the current time.

在您的主循环中,获取时间并将其与您上次调用该函数的时间(在声明时初始化为“现在”)进行比较。如果它大于您的时间间隔,则调用您的函数并将“上次调用”变量设置为当前时间。

回答by Ahmed Saleh

There are two approaches: 1.Asynchronous 2. Synchronous

有两种方法: 1.Asynchronous 2. Synchronous

  1. Assuming that you are using Win32, C++. You can use Win32 API SetTimer

    UINT_PTR timerid = SetTimer(NULL, 0, milliseconds, &callback);

  2. If you would like a Polling Approach You would better use something like that

      for(;;) 
        {
    
        Say_Hello();
        // Sleep for 50*1000ms
        Sleep(50000);
    
        }
    
  1. 假设您使用的是 Win32、C++。您可以使用 Win32 API SetTimer

    UINT_PTR timerid = SetTimer(NULL, 0, 毫秒, &callback);

  2. 如果您想要轮询方法,您最好使用类似的方法

      for(;;) 
        {
    
        Say_Hello();
        // Sleep for 50*1000ms
        Sleep(50000);
    
        }
    

回答by Mushy

For a timer more cross-platform and utilizing the c++ STL, take a look at C++ Cross-Platform High-Resolution Timer.

对于更跨平台并使用 c++ STL 的计时器,请查看C++ Cross-Platform High-Resolution Timer

From there, simply create and call a function in a loop every 10 ~ 50 seconds using two of those cross-platform timers mentioned above.

从那里,只需使用上面提到的两个跨平台计时器,每 10 到 50 秒在循环中创建和调用一个函数。