
以下是一些关于如何设置GetTickCount( )
为间隔计时器的代码:
首先你有时间,
StartTime = GetTickCount( )
然后你添加另一个计时器
EndTime = GetTickCount( )
并从 StartTime 中减去 EndTime
DeltaTime = EndTime - StartTime
然后你DeltaTime
与EveryMillisecondTask
. 如果结果是true
,您将生成一个与您设置的 switch 语句中的数字相对应的随机数,然后调用GCChatTargetSend( )
.
if ( DeltaTime >= EveryMillisecondTask ){
int x = rand() % 4;
switch(x){
// do stuff
}
}
以下是完整的代码清单 GetTickCount( )
:
#include <time.h>
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
void GCChatTargetSend( string message );
int main() {
int EveryMillisecondTask=1000; // 1 second = 1000 milliseconds
int StartTime = GetTickCount();
srand (time(NULL));
cout<<"Welcome to GetTickCount() interval timer \n \n";
cout<<"Interval set to "<< EveryMillisecondTask <<" milliseconds \n";
while( true ){
int EndTime = GetTickCount();
int DeltaTime = EndTime - StartTime;
// test to see if EveryMillisecondTask matches time
if ( DeltaTime >= EveryMillisecondTask ){
// generate random number
int x = rand() % 4;
cout<<"\nRandom X= "<< x+1 <<"\n";
// switch x
switch(x){
case 0:
GCChatTargetSend("String message 1 Here ");
break;
case 1:
GCChatTargetSend("String message 2 Here ");
break;
case 2:
GCChatTargetSend("String message 3 Here ");
break;
case 3:
GCChatTargetSend("String message 4 Here ");
break;
default:
break;
}
// reset time
StartTime = GetTickCount();
EndTime = GetTickCount();
}
}//while
return 0;
}
void GCChatTargetSend( string message ){
cout<<message<<" \n";
}
以下是如何使用 Windows 自己的settimer( )
功能执行间隔计时器。
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx
示例代码settimer( )
:
#define STRICT 1
#include <windows.h>
#include <iostream.h>
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime);
int main(int argc, char *argv[], char *envp[]){
int Counter=0;
MSG Msg;
int timeInMilliseconds = 2000;
cout<<"Welcome to SetTimer( ) interval timer \n \n";
cout<<"Interval set to "<< timeInMilliseconds <<" milliseconds \n\n\n";
UINT TimerId = SetTimer(NULL, 0, timeInMilliseconds, &TimerProc); //2000 milliseconds
cout << "TimerId: " << TimerId << '\n';
if (!TimerId) return 16;
while (GetMessage(&Msg, NULL, 0, 0)){
++Counter;
if (Msg.message == WM_TIMER) cout << "Counter: " << Counter << "; timer message\n";
else
cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
DispatchMessage(&Msg);
}
KillTimer(NULL, TimerId);
return 0;
}
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime){
cout << "CALLBACK " << dwTime << " \n\n";
cout.flush();
}