延迟执行代码

delayed execution of code

本文关键字:代码 执行 延迟      更新时间:2023-10-16

假设我们在一个函数中,每当按下鼠标按钮时都会调用

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

}

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

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

这是我的类(它并不完美,但你可以看看它是如何实现的(,用于控制套接字后面程序的心跳。当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;
    };