Windows 下, SetTimer 定时器的研究.

一直很困惑一个问题:

我设置了一个10秒的定时器,可是被调用的函数要花费30秒,

那待调用的函数第二次是什么时候调用的呢?

20秒, 40秒, 还是50秒呢....

所以我进行了实验.

我写了一个类 CExecSqlTimer, 这里类封装了.setitime.

这个类创建一个线程来调用待调用函数.

1 CExecSqlTimer *time = new CExecSqlTimer;
2 time->SetInterval(10 * 1000);
3 time->Start();

待调用函数:

 1 BOOL CExecSqlTimer::OnTimer()
 2 {
 3 
 4     static DWORD dwTick = ::GetTickCount();
 5     static int i = 1;
 6     DWORD t = ::GetTickCount() - dwTick;
 7     CString str;
 8     str.Format(" 第 %d 次 %d ms调用.", i, t);
 9     TRACE("%s
", str);
10     Sleep(30000);
11     str.Format(" 第 %d 次 %d ms 执行完.", i, ::GetTickCount() - dwTick);
12     TRACE("%s
", str);
13     i++;
14     return TRUE;
15 }

关键看执行完代码:

 110 ms调用.
 2130000 ms 执行完.
 3240000 ms调用.
 4270000 ms 执行完.
 5380000 ms调用.
 63110016 ms 执行完.
 74120016 ms调用.
 84150032 ms 执行完.
 95160032 ms调用.
105190032 ms 执行完.
116200032 ms调用.
126230047 ms 执行完.
137240047 ms调用.
147270063 ms 执行完.

事实就放在这里了哈~

想要10秒执行一次,那你就在函数里开个线程去处理你的内容把~

  
原文地址:https://www.cnblogs.com/SamRichard/p/4916379.html