Windows API Reference

Timer Objects

Timer objects are kernel objects that can be used to notify a thread after a specified interval or at a specific time. They are useful for scheduling tasks, implementing delays, or synchronizing operations.

Overview

A timer object is associated with a timer queue. When a timer expires, a user-defined callback function is invoked. Timer objects can be periodic or one-shot.

Key Concepts

Creating and Managing Timer Objects

The following functions are commonly used to create and manage timer objects:

CreateWaitableTimerEx

Creates or opens a timer- பெறுobject. This function allows specifying an extended attributes parameter.


HANDLE CreateWaitableTimerEx(
  LPSECURITY_ATTRIBUTES lpTimerAttributes,
  LPCWSTR lpTimerName,
  DWORD dwFlags,
  DWORD dwDesiredAccess
);
            

SetWaitableTimer

Starts or replaces the current setting of a waitable timer object. The system sets the timer object's state to signaled when the due time arrives.


BOOL SetWaitableTimer(
  HANDLE       hTimer,
  const LARGE_INTEGER *lpDueTime,
  LONG         lPeriod,
  PTIMER_CALLBACK pfnCompletionRoutine,
  LPVOID       lpArgToCompletionRoutine,
  BOOL         fResume
);
            

CancelWaitableTimer

Cancels a pending wait operation on the specified waitable timer object. If the timer has already expired, this function does not affect its state.


BOOL CancelWaitableTimer(
  HANDLE hTimer
);
            

Timer Callback Functions

When a timer expires and a callback routine is specified, the system calls the callback function.


VOID CALLBACK TimerCallback(
  LPVOID lpArg,
  DWORD  dwTimerLowValue,
  DWORD  dwTimerHighValue
);
            
Important: Timer callback functions should be designed to execute quickly. Avoid performing lengthy operations or blocking calls within a callback.

Example Usage

The following snippet demonstrates creating a waitable timer that fires once after 5 seconds.


HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
if (hTimer == NULL) {
    // Handle error
    return 1;
}

// Set the timer to fire after 5 seconds (5000 milliseconds)
// Negative value means relative time
LARGE_INTEGER liDueTime;
liDueTime.QuadPart = -5000LL * 10000LL; // Convert milliseconds to 100-nanosecond intervals

if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, FALSE)) {
    // Handle error
    CloseHandle(hTimer);
    return 1;
}

// Wait for the timer to become signaled
WaitForSingleObject(hTimer, INFINITE);

// Timer has expired
// ...

CloseHandle(hTimer);
            

Related Topics