【问题标题】:C++: comparing current time to next work timeC ++:将当前时间与下一个工作时间进行比较
【发布时间】:2018-01-23 23:42:58
【问题描述】:

我正在开发一个自动化程序。这个想法是,在执行一个动作之后,它会增加应该执行下一个动作的时间。我选择了这种方法而不是简单的Sleep() 语句,因为我正在等待执行各种操作的用户键盘输入。

我遇到的问题是std::chrono::steady_clock::now() > next_work_period 似乎总是评估为真,因此没有等待期。

这是我第一次使用这些功能。感谢您的帮助!

auto next_work_period = std::chrono::steady_clock::now();

    while (1) {

        // To keep disk usage low, 100 may need to be changed
        Sleep(100);

        // If current time is time to do next action
        if (std::chrono::steady_clock::now() > next_work_period) {

            std::cout << "Has been 20 seconds" << endl;

            // Calculate next click time, 20 seconds from now
            next_work_period += std::chrono::milliseconds((20) * 1000);
        }
    }

【问题讨论】:

    标签: c++ time chrono


    【解决方案1】:

    直到下一个工作时间怎么样?像这样:

    auto next_work_period = std::chrono::steady_clock::now();
    
    while (1) {
    
        std::this_thread::sleep_until(next_work_period);
    
        doTheThing();
    
        // Calculate next click time, 20 seconds from now
        next_work_period += std::chrono::seconds(20);
    }
    

    【讨论】:

    • 这是否仍然允许我在睡眠期间正确检查按键直到,或者它是否像常规睡眠语句一样在该行暂停?
    • @Grehgous 这只会休眠当前线程。所有其他线程都可以正常运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多