在Visual C++(VC)编程中,有多种方法可以实现定时功能。以下是一些常见的定时器方法:
- Sleep函数:
Sleep
是Windows API中的一个函数,它使当前线程暂停执行指定的时间段。语法:
Sleep(seconds);
示例:
#include <windows.h>
#include <iostream>
int main() {
std::cout << "Starting sleep for 5 seconds..." << std::endl;
Sleep(5000); // Sleep for 5000 milliseconds (5 seconds)
std::cout << "Finished sleeping." << std::endl;
return 0;
}
- Sleep_until函数:
Sleep_until
是Windows API中的一个函数,它使当前线程暂停执行,直到到达指定的时间点。语法:
Sleep_until(date);
示例:
#include <windows.h>
#include <iostream>
int main() {
std::cout << "Starting sleep until 5 seconds from now..." << std::endl;
FILETIME ftStart, ftCurrent;
GetSystemTimeAsFileTime(&ftStart);
SleepUntil(ftCurrent); // Sleep until the system time is 5 seconds from ftStart
std::cout << "Finished sleeping." << std::endl;
return 0;
}
- CreateWaitableTimer函数:
CreateWaitableTimer
是Windows API中的一个函数,用于创建一个可等待的定时器对象。示例:
#include <windows.h>
#include <iostream>
int main() {
HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
if (hTimer == NULL) {
std::cerr << "CreateWaitableTimer failed: " << GetLastError() << std::endl;
return 1;
}
LARGE_INTEGER liDueTime;
liDueTime.QuadPart = -50000000LL; // 5 seconds in 100-nanosecond intervals
if (!SetWaitableTimer(hTimer, &liDueTime, 5000, TimerCallback, NULL, FALSE)) {
std::cerr << "SetWaitableTimer failed: " << GetLastError() << std::endl;
CloseHandle(hTimer);
return 1;
}
std::cout << "Waiting for 5 seconds..." << std::endl;
WaitForSingleObject(hTimer, INFINITE);
std::cout << "Finished waiting." << std::endl;
CloseHandle(hTimer);
return 0;
}
VOID CALLBACK TimerCallback(PVOID lpParam, BOOLEAN TimerOrWaitFired) {
std::cout << "Timer callback called." << std::endl;
}
- CreateEvent函数:
CreateEvent
是Windows API中的一个函数,用于创建一个命名或匿名的事件对象。示例:
#include <windows.h>
#include <iostream>
int main() {
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (hEvent == NULL) {
std::cerr << "CreateEvent failed: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Waiting for event..." << std::endl;
WaitForSingleObject(hEvent, INFINITE);
std::cout << "Event received." << std::endl;
CloseHandle(hEvent);
return 0;
}
这些方法可以根据具体需求进行选择和使用。在实际应用中,可能需要结合其他Windows API函数来实现更复杂的定时任务。