windows-timer

c++ 11

https://github.com/eglimi/cpptime

CppTime::timer_id timerId = pwnd->m_curInfo.tokenTimer.add(CppTime::clock::now() + std::chrono::hours(24), 
[=](CppTime::timer_id) {
g_logger->info("cmdType_frontend_login: frontend token timeout fired token={},timerId={}", token, timerId);
pwnd->m_mapFrontConnInfo.erase(token);
pwnd->m_curInfo.tokenTimer.remove(timerId);
});

MFC

#define	TIMER_ACTIVE_COUNTDOWN		100

//1s
SetTimer(TIMER_ACTIVE_COUNTDOWN, 1000 * 1, NULL);

//在响应Timer事件并处理时,界面是无响应状态,所以这里要注意,如果处理时间长久不能用Timer,要用线程。
void CMerchantBind::OnTimer(UINT_PTR nIDEvent)
{
if (nIDEvent == TIMER_ACTIVE_COUNTDOWN)
{
...
KillTimer(TIMER_ACTIVE_COUNTDOWN);
}

CDialog::OnTimer(nIDEvent);
}

不需要消息循环的Timer


BOOL WINAPI DeleteTimerQueueTimer(
_In_opt_ HANDLE TimerQueue,
_In_ HANDLE Timer,
_In_opt_ HANDLE CompletionEvent
);

/*
CompletionEvent [in, optional]
A handle to the event object to be signaled when the system has canceled the timer and all callback functions have completed. This parameter can be NULL.

If this parameter is INVALID_HANDLE_VALUE, the function waits for any running timer callback functions to complete before returning.

If this parameter is NULL, the function marks the timer for deletion and returns immediately. If the timer has already expired, the timer callback function will run to completion. However, there is no notification sent when the timer callback function has completed. Most callers should not use this option, and should wait for running timer callback functions to complete so they can perform any needed cleanup.
So if you want to call the API in the timer callback function, please don't set the value of CompletionEvent to INVALID_HANDLE_VALUE.
*/

//这个timer需要消息循环,如果在dll里面使用,可以用 CreateTimerQueueTimer

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
 
/* Functions in your dll. */
HANDLE g_hTimer;
 
VOID CALLBACK TimerCallback(PVOID lpParameter, BOOLEAN reserved)
{
    /* Remember this callback is executed in a different thread,
     * so use synchronization if needed. */
 
DeleteTimerQueueTimer(NULL, g_hTimer, NULL);
    printf("Timer called\n");
}
 
void Start(void)
{
    PVOID param    = NULL; /* You can use this to pass a value to the callback. */
    DWORD interval = 100/* Interval in milliseconds. */
 
    CreateTimerQueueTimer(&g_hTimer, NULL, TimerCallback, param, interval, interval, 0);
}
 
void End(void)
{
    DeleteTimerQueueTimer(NULL, g_hTimer, INVALID_HANDLE_VALUE);
}
 
 
/* Calling function. */
int main(void)
{
    Start();
 
    getchar();
 
    End();
 
    getchar();
    return 0;
}