c ++ - 延迟执行代码

时间:2016-08-05 11:15:20

标签: c++ timeout

假设我们处于一个按下鼠标按钮时被调用的函数

static inline LRESULT CALLBACK WndProc(const int code, const WPARAM wParam, const LPARAM lParam){


}

我现在想要在没有按下按钮5秒后执行一些代码。如果在2秒后,用户单击鼠标按钮,则应重置“计时器”并再等5秒钟。

这甚至可以用C ++完成吗?如果我使用Sleep(5000),如果在其间按下另一个按钮,则无法阻止代码运行。

1 个答案:

答案 0 :(得分:0)

这是我的课程(它不完美,但你可以看看它是如何完成的)来控制套接字后面的程序心跳。当调用beat()方法时,计时器被重置"。

    class HeartbeatController
    {
    private:
        using ms = std::chrono::milliseconds;
    public:
        HeartbeatController(std::function<void()> &heartbeatLostCallback, 
                            const ms &panicTime = ms{5000}, //time in milliseconds, after which panic code will be executed
                            const ms &checkDuration = ms{ 1000 }) noexcept :
            heartbeatLostCallback{ heartbeatLostCallback }
        {}

        ~HeartbeatController() = default;

        HeartbeatController(HeartbeatController &&other) :
            heartbeatLostCallback{ std::move(other.heartbeatLostCallback) },
            loopThread{ std::move(other.loopThread) },
            lastBeat{ std::move(other.lastBeat) },
            panicTime{ std::move(other.panicTime) },
            checkDuration{ std::move(other.checkDuration) }
        {}

        HeartbeatController& operator=(HeartbeatController &&other)
        {
            heartbeatLostCallback = std::move(other.heartbeatLostCallback);
            loopThread = std::move(other.loopThread);
            lastBeat = std::move(other.lastBeat);
            panicTime = std::move(other.panicTime);
            checkDuration = std::move(other.checkDuration);

            return *this;
        }

        HeartbeatController(const HeartbeatController&) = delete;
        HeartbeatController& operator=(const HeartbeatController&) = delete;

        void interrupt() noexcept
        {
            interrupted = true;
        }

        void beat() noexcept
        {
            lastBeat = Clock::now();
        }

        void start()
        {
            auto loop = [this]
            {
                while (!interrupted)
                {
                    if (Clock::now() - lastBeat > panicTime)
                        heartbeatLostCallback(); //here you can insert some your code which you wanna execute after no beat() for panicTime duration

                    std::this_thread::sleep_for(checkDuration);
                }
            };

            lastBeat = Clock::now();

            loopThread = std::thread{ loop };
        }

    private:
        using Clock = std::chrono::system_clock;

        std::reference_wrapper<std::function<void()>> heartbeatLostCallback;
        std::thread loopThread;

        std::chrono::time_point<Clock> lastBeat;
        std::chrono::milliseconds panicTime;
        std::chrono::milliseconds checkDuration;

        bool interrupted = false;
    };