计时器

 1 // 计时器.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <windows.h>
 6 #include <iostream>
 7 #include <time.h>
 8 using namespace std;
 9 
10 BOOL __IsLoop = TRUE;
11 
12 
13 void GetSystemTime();
14 DWORD WINAPI ThreadProc(LPVOID parameterData);
15 
16 
17 int main()
18 {
19     HANDLE ThreadHandle = CreateThread(
20         NULL,
21         0,
22         (LPTHREAD_START_ROUTINE)ThreadProc,
23         NULL,
24         0,
25         NULL
26         );
27 
28     printf("input any key to exit\r\n");
29     getchar();
30     __IsLoop = FALSE;
31     WaitForSingleObject(ThreadHandle, INFINITE);
32 
33     if (ThreadHandle != NULL)
34     {
35         CloseHandle(ThreadHandle);
36         ThreadHandle = NULL;
37     }
38 
39     
40     return 0;
41 }
42 
43 DWORD WINAPI ThreadProc(LPVOID parameterData)
44 {
45     LARGE_INTEGER DueTime;
46     DueTime.QuadPart = -10'000'000LL;//倒计时1秒
47 
48     HANDLE TimeHandle = NULL;
49     TimeHandle =
50         CreateWaitableTimer(
51             NULL,
52             //TRUE, //BOOL  bManualReset
53             FALSE,
54             NULL
55         );
56 
57 
58     //同步事件(synchronizationEvent)
59     //当事件对象为激发时,如遇到KeWaitForXX等内核函数,事件对象则自动变回未激发态
60     //通知事件(NotificationEvent)
61     //当事件对象为激发时,如遇到KeWaitForXX等内核函数,事件对象则不会自动变回未激发态
62     
63     while (__IsLoop)
64     {
65         if (!SetWaitableTimer(TimeHandle, &DueTime, 0, NULL, NULL, 0))
66         {
67             printf("SetWaitableTimer FAIL: %d  \r\n", GetLastError());
68             return 0;
69         }
70 
71         BOOL IsOk = WaitForSingleObject(TimeHandle, INFINITE);
72         IsOk -= WAIT_OBJECT_0;
73 
74         if (IsOk==0)
75         {
76             system("cls");
77             GetSystemTime();
78             printf("Timer was signaled\r\n");
79         }
80         else
81         {
82             break;
83         }
84     }
85     CancelWaitableTimer(TimeHandle);
86     CloseHandle(TimeHandle);
87     TimeHandle = NULL;
88     printf("ThreadProc Exit\r\n");
89 
90     return 0;
91 }
92 
93 void GetSystemTime()
94 {
95     time_t t = time(0);
96     char tmp[64];
97     strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z", localtime(&t));
98     puts(tmp);
99 }

 

posted on 2017-09-08 21:18  czhang4  阅读(156)  评论(0编辑  收藏  举报