用定时器执行回调函数

简单使用

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

VOID CALLBACK run(void *arg, DWORD timelow, DWORD timehigh)
{
	DWORD index = *(DWORD *)arg;						   //参数进行转换
	printf("执行第%d次\n", index);
}

int main(int argc, char *argv[])
{
	HANDLE timer = CreateWaitableTimer(NULL, TRUE, "xy");			  //创建定时器
	if (timer == NULL)
	{
		printf("创建定时器失败!\n");
	}
	LARGE_INTEGER mytime;
	mytime.QuadPart = -50000000;  //0.1微妙

	DWORD dwparma = 1;

	if (SetWaitableTimer(timer, &mytime, 1000, run, &dwparma, FALSE))	  //设置定时器1秒钟执行run函数(回调函数)一次
	{
		printf("等待5秒钟调用run函数\n");
		for (int i = 0; i < 5; i++, dwparma++)
		{
			SleepEx(INFINITE, TRUE); 
		}
	}

	CancelWaitableTimer(timer);                                               //取消定时器
	CloseHandle(timer);
	system("pause");
	return 0;
}


秋风 2016-06-29