• Windows timeSetEvent定时器


    Windows timeSetEvent定时器

    参考微软文档

    参考博客

    函数描述

    MMRESULT timeSetEvent(
       UINT uDelay,
       UINT uResolution,
       LPTIMECALLBACK lpTimeProc,
       DWORD_PTR dwUser,
       UINT fuEvent
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • udelay事件延迟,以毫秒为单位。如果该值不在定时器支持的最小和最大事件延迟的范围内,则该函数返回错误。最大值是1000秒。
    • uResolution定时器事件的解析度,以毫秒为单位。分辨率随着较小的值而增加; 分辨率为0表示定期事件应该尽可能准确地发生。但是,为了减少系统开销,您应该使用适合您的应用程序的最大值。
    • lpTimeProc指向一个回调函数的指针,该函数在单个事件到期时调用一次,或者在周期性事件到期时定期调用。如果fuEvent指定了TIME_CALLBACK_EVENT_SETTIME_CALLBACK_EVENT_PULSE标志,则lpTimeProc参数将被解释为事件对象的句柄。该事件将在单个事件完成后定期执行,或定期事件完成后进行。对于fuEvent的任何其他值,lpTimeProc参数是指向LPTIMECALLBACK类型的回调函数的指针。
    • dwUser用户提供的回调数据。
    • fuEvent定时器事件类型。该参数可能包含以下值之一。
      • TIME_ONESHOT在uDelay毫秒后发生一次事件。
      • TIME_PERIODIC事件每uDelay毫秒发生一次。

    回调函数

    参考:微软文档

    typedef void (CALLBACK TIMECALLBACK)(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2);
    typedef TIMECALLBACK FAR *LPTIMECALLBACK;
    
    • 1
    • 2
    • uTimerID,定时器ID
    • uMsg,保留
    • dwUser,用户自定义数据
    • dw1,保留
    • dw2,保留

    头文件及库依赖

    #include 
    #include 
    
    • 1
    • 2

    静态库Winmm.lib动态库Winmm.dll

    示例

    #include 
    #include 
    #include 
    #include 
    
    void cb(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
    {
        std::cout << "回调线程号:" << std::this_thread::get_id() << std::endl;
        std::cout << "计时器ID:" << uTimerID << std::endl;
    }
    
    int main()
    {
        std::cout << "当前线程号:" << std::this_thread::get_id() << std::endl;
        MMRESULT tmId = timeSetEvent(500, 1, cb, NULL, TIME_ONESHOT);
        if (tmId == NULL) {
            std::cout << "定时器创建失败" << std::endl;
            return 0;
        }
        Sleep(1000);
        timeKillEvent(tmId);
        std::cout << "程序结束" << std::endl;
        return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    cmake_minimum_required(VERSION 3.18)
    project("Timer" LANGUAGES CXX)
    
    if(MSVC)
        add_compile_options("/source-charset:utf-8")
    endif()
    
    add_executable(${PROJECT_NAME} main.cpp)
    
    target_link_libraries(${PROJECT_NAME} PUBLIC "Winmm.lib")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    MySQL 教程 2.4
    [附源码]Python计算机毕业设计SSM焦作旅游网站(程序+LW)
    最详细Pycharm远程代码调试配置方案【针对GPU集群】
    三分钟学会数据结构顺序表
    备忘录模式 行为型模式之八
    元宇宙数字藏品,打造数字经济产业,实现全新业态升级
    这个简单的小功能,半年为我们产研团队省下213个小时
    10月Java行情 回暖?
    TypeError: __init__() got an unexpected keyword argument ‘pretrained_cfg‘
    【CSDN高校社区&兰州理工大学】# 新学期,新Flag # 开学季征文活动
  • 原文地址:https://blog.csdn.net/izwmain/article/details/133763666