﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-宁波的人的VC</title><link>http://www.cppblog.com/archer-xu/</link><description /><language>zh-cn</language><lastBuildDate>Tue, 09 Jun 2026 20:25:53 GMT</lastBuildDate><pubDate>Tue, 09 Jun 2026 20:25:53 GMT</pubDate><ttl>60</ttl><item><title>Windows定时器管理</title><link>http://www.cppblog.com/archer-xu/archive/2008/07/07/55530.html</link><dc:creator>徐超</dc:creator><author>徐超</author><pubDate>Mon, 07 Jul 2008 05:14:00 GMT</pubDate><guid>http://www.cppblog.com/archer-xu/archive/2008/07/07/55530.html</guid><wfw:comment>http://www.cppblog.com/archer-xu/comments/55530.html</wfw:comment><comments>http://www.cppblog.com/archer-xu/archive/2008/07/07/55530.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/archer-xu/comments/commentRss/55530.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/archer-xu/services/trackbacks/55530.html</trackback:ping><description><![CDATA[目标：游戏编程中经常需要使用定时器，多个定时器往往同时在运行，所以希望有一个独立的类，专门管理定时器。并支持console模式，因为服务器很有可能以console模式运行。客户端可以方便地使用定时器，虽然SetTimer函数的第四个参数可以设置回调函数，但这样每个使用的客户都必须实现一个静态或全局的函数作为回调函数，使用起来很不方便。<br><br>分析：console模式没有类似窗口模式的GetMessage函数，不能获取WM_TIMER消息。经过研究发现Console模式下也可以使用GetMessage函数，于是决定开一个线程专门用来GetMessage，当客户代码需要设定定时器时，直接使用SetTimer函数设定定时器。通过试验发现这么做GetMessage不能获得WM_TIMER消息。因为SetTimer的线程与GetMessage不是同一个线程。使用PostThreadMessage给等待在GetMessage的线程发自定义消息，让等待在GetMessage消息的线程解析PostThreadMessage参数，然后设置或取消定时器，这样，设定与获取定时器的线程就是同一个的了。<br>以下是代码:<br>/* ITimer.h 所有希望使用定时器的客户必须继承ITimer接口，实现OnTimerEnd函数，当定时器触发时会调用该函数 */<br>#ifndef _ITIMER_H__<br>#define _ITIMER_H__<br><br>class ITimer<br>{<br>public:<br>&nbsp;&nbsp;&nbsp; virtual void OnTimeEnd(int iTimerId) = 0;<br>&nbsp;&nbsp;&nbsp; virtual ~ITimer() {};<br>};<br><br>#endif /* _ITIMER_H__ */<br><br>/* ZTimer.h 定时器管理器类的头文件，两个公共方法StartTimer和EndTimer，相信不说也知道作用了 */<br>#ifndef _ZTIMER_H__<br>#define _ZTIMER_H__<br><br>#include &lt;map&gt;<br>using namespace std;<br><br>#include "Mutex.h"<br>#include "ITimer.h"<br><br>class ZTimer<br>{<br>public:<br>&nbsp;&nbsp;&nbsp; ZTimer();<br><br>&nbsp;&nbsp;&nbsp; int StartTimer(int iMilliSec, ITimer *pITimer);<br>&nbsp;&nbsp;&nbsp; void EndTimer(int iTimer);<br><br>protected:<br>&nbsp;&nbsp;&nbsp; void CreateSchedulerThread();&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; static void _stdcall TimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime);<br>&nbsp;&nbsp;&nbsp; static DWORD _stdcall SchedulerThread(LPVOID pVoid);<br><br>private:<br>&nbsp;&nbsp;&nbsp; ZMutex m_mutex; // 用于支持多线程，对CRITICAL_SECTION的简单封装<br>&nbsp;&nbsp;&nbsp; DWORD m_dwThreadId; // 阻塞在GetMessage函数的线程ID，在PostThreadMessage中使用<br>&nbsp;&nbsp;&nbsp; map&lt;int, ITimer *&gt; m_mapIdITimer; // 每个TimerId对应的客户，用于定时器发生后调用OnTimeEnd<br>&nbsp;&nbsp;&nbsp; HANDLE m_hSchedulerRun; //　用于保证GetMessage线程先于调用StartTimer的线程运行，不知是否还有更好的方法<br>&nbsp;&nbsp;&nbsp; HANDLE m_hEventGetTimerId; // 得到并返回TimerId<br>&nbsp;&nbsp;&nbsp; int m_iTimerId;<br>}; <br><br>#endif /* _ZTIMER_H__ */<br><br>/* ZTimer.cpp ZTimer.h的具体实现 */<br>#include &lt;windows.h&gt;<br>#include "ZTimer.h"<br><br>// wparam 为VOTE_ID VOTE_TIME, lparam 为ITimer<br>#define START_TIMER_MSG&nbsp;&nbsp;&nbsp; WM_USER + 1<br>// wparam 为timer id值<br>#define END_TIMER_MSG&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WM_USER + 2<br>// 最大等待时间<br>#define MAX_WAIT_TIME&nbsp;&nbsp; 2000<br><br>ZTimer::ZTimer()<br>{<br>&nbsp;&nbsp;&nbsp; // 保证子线程先运行<br>&nbsp;&nbsp;&nbsp; m_hSchedulerRun = CreateEvent(NULL, true, false, NULL);<br>&nbsp;&nbsp;&nbsp; // 获取Timer ID<br>&nbsp;&nbsp;&nbsp; m_hEventGetTimerId = CreateEvent(NULL, false, false, NULL);<br><br>&nbsp;&nbsp;&nbsp; CreateSchedulerThread();<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; if (WaitForSingleObject(m_hSchedulerRun, MAX_WAIT_TIME) == WAIT_TIMEOUT)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to do<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("ztimer error:---------------------------------------------------****\n");<br>&nbsp;&nbsp;&nbsp; }<br>}<br><br>int ZTimer::StartTimer(int iMilliSec, ITimer *pITimer)<br>{<br>&nbsp;&nbsp;&nbsp; m_mutex.Lock();<br><br>&nbsp;&nbsp;&nbsp; PostThreadMessage(m_dwThreadId, START_TIMER_MSG, (WPARAM)iMilliSec, (LPARAM)pITimer);<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; if (WaitForSingleObject(m_hEventGetTimerId, MAX_WAIT_TIME) == WAIT_OBJECT_0)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_mapIdITimer.insert(make_pair(m_iTimerId, pITimer));<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_mutex.Unlock();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return m_iTimerId;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to do, error<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("start timer error:---------------------------------------------------****\n");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_mutex.Unlock();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return 0;<br>&nbsp;&nbsp;&nbsp; }<br>}<br><br>void ZTimer::EndTimer(int iTimer)<br>{<br>&nbsp;&nbsp;&nbsp; m_mutex.Lock();<br>&nbsp;&nbsp;&nbsp; PostThreadMessage(m_dwThreadId, END_TIMER_MSG, iTimer, 0);<br><br>&nbsp;&nbsp;&nbsp; if (WaitForSingleObject(m_hEventGetTimerId, MAX_WAIT_TIME) == WAIT_OBJECT_0)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; m_mapIdITimer.erase(iTimer);<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to do, error<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; m_mutex.Unlock();<br>}<br><br>void ZTimer::TimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)<br>{<br>}<br><br>void ZTimer::CreateSchedulerThread()<br>{<br>&nbsp;&nbsp;&nbsp; CreateThread(NULL, 0, SchedulerThread, (void *)this, 0, &amp;m_dwThreadId);&nbsp;&nbsp; <br>}<br><br>// 调度线程函数，用于阻塞在GetMessage中，处理WM_TIMER消息<br>DWORD ZTimer::SchedulerThread(LPVOID pVoid)<br>{<br>&nbsp;&nbsp;&nbsp; ZTimer *pThis = (ZTimer *)pVoid;<br><br>&nbsp;&nbsp;&nbsp; MSG msg;<br><br>&nbsp;&nbsp;&nbsp; SetEvent(pThis-&gt;m_hSchedulerRun);<br><br>&nbsp;&nbsp;&nbsp; while(GetMessage(&amp;msg, NULL, 0, 0)) <br>&nbsp;&nbsp;&nbsp; { <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (msg.message == START_TIMER_MSG)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pThis-&gt;m_iTimerId = (int)SetTimer(NULL, 0, (UINT)msg.wParam, TimerProc);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SetEvent(pThis-&gt;m_hEventGetTimerId);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else if (msg.message == END_TIMER_MSG)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; KillTimer(NULL, msg.wParam);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else if (msg.message == WM_TIMER)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ITimer *pTimer = pThis-&gt;m_mapIdITimer[(int)msg.wParam];<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (pTimer != NULL)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pTimer-&gt;OnTimeEnd((int)msg.wParam);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("wm_timer error\n");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; TranslateMessage(&amp;msg);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DispatchMessage(&amp;msg);<br>&nbsp;&nbsp;&nbsp; } <br><br>&nbsp;&nbsp;&nbsp; return 0;<br>} 
<img src ="http://www.cppblog.com/archer-xu/aggbug/55530.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/archer-xu/" target="_blank">徐超</a> 2008-07-07 13:14 <a href="http://www.cppblog.com/archer-xu/archive/2008/07/07/55530.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>