[C/C++]windows定时器

本文展示了一个使用Windows API创建事件、定时器队列及定时器的C语言程序实例。通过该示例,读者可以了解到如何利用CreateEvent、CreateTimerQueue、CreateTimerQueueTimer等函数实现基于Windows系统的定时任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <windows.h>

VOID CALLBACK VirtualIDCallback(PVOID lpParameter, BOOLEAN TimeOrWaitFired);
int main()
{
        HANDLE handle = NULL;
        HANDLE hTimer = NULL;
        HANDLE hTimerQueue = NULL;
        int arg = 0;
        handle = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (NULL == handle)
        {
            printf("CreateEvent失败\n");
            return 1;
        }
        hTimerQueue = CreateTimerQueue();
        if (NULL == hTimerQueue)
        {
            printf("CreateTimeQueue失败\n");
            return 1;
        }
        if (!CreateTimerQueueTimer(&hTimer, hTimerQueue, WAITORTIMERCALLBACK(VirtualIDCallback), &arg, 5000, 10000, NULL))
        {
            printf("CreateTimeQueueTimer失败\n");
            return 1;
        }
        if (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0)
        {
            printf("WaitForSingObject失败\n");
            return 1;
        }
        CloseHandle(handle);
        if (hTimer)
        {
            if (!DeleteTimerQueueTimer(hTimerQueue, hTimer, INVALID_HANDLE_VALUE))
            {
                Sleep(1000);
                if (!DeleteTimerQueueTimer(hTimerQueue, hTimer, INVALID_HANDLE_VALUE))
                    return 0;
            }
        }
        return 0;
}

VOID CALLBACK VirtualIDCallback(PVOID lpParameter, BOOLEAN TimeOrWaitFired)
{
    // 定时器逻辑代码
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值