How to create timer events using C++ 11?

前端 未结 5 1060
执念已碎
执念已碎 2020-11-27 02:24

How to create timer events using C++ 11?

I need something like: “Call me after 1 second from now”.

Is there any library?

5条回答
  •  借酒劲吻你
    2020-11-27 03:04

    If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

    template
    static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
    {
        CloseThreadpoolTimer(timer);
        std::unique_ptr callable(reinterpret_cast(context));
        (*callable)();
    }
    
    template 
    void call_after(T callable, long long delayInMs)
    {
        auto state = std::make_unique(std::move(callable));
        auto timer = CreateThreadpoolTimer(timer_fired, state.get(), nullptr);
        if (!timer)
        {
            throw std::runtime_error("Timer");
        }
    
        ULARGE_INTEGER due;
        due.QuadPart = static_cast(-(delayInMs * 10000LL));
    
        FILETIME ft;
        ft.dwHighDateTime = due.HighPart;
        ft.dwLowDateTime = due.LowPart;
    
        SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
        state.release();
    }
    
    int main()
    {
        auto callback = []
        {
            std::cout << "in callback\n";
        };
    
        call_after(callback, 1000);
        std::cin.get();
    }
    

提交回复
热议问题