c++线程、定时器的使用

本文介绍了一个基于Windows API的定时器线程类的实现,该类能够创建定时任务并执行回调函数。通过示例代码展示了如何使用这个类来设置定时器,并在指定的时间间隔后调用特定的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装成了一个类,以便很好的进行参数传递使用。

TimerThread.h

#pragma once
#ifndef APLAYER_TIMERTHREAD_H
#define APLAYER_TIMERTHREAD_H
#include <Windows.h>
#include <process.h>  

class cTimerThread {
public:
	cTimerThread()
	{
	}
	~cTimerThread()
	{
	//	KillTimer();
	}
	int    CreateTimer(unsigned int interval, PTIMERAPCROUTINE func, void* lpParam);
//	void   KillTimer();

public:
	std::string name;
	std::string job_id;
	bool        _bRunning;
private:
	static DWORD WINAPI timerThread(LPVOID lpParam);
	HANDLE                _hTimer;
	int                    _nInterval;
	HANDLE                _hEvent;
	void*                _lpParam;

	PTIMERAPCROUTINE    _callbackFunc;
	HANDLE                _hThread;
	DWORD                _dwThread;
	
};
#endif

TimerThread.cpp

#include<iostream>
#include<Windows.h>
#include "TimerThread.h"
#include <thread>

using namespace std;

int a = 0;
VOID APIENTRY TimerAPCRoutine(PVOID pvArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)

{
	
	a++;
	cTimerThread* ctt = (cTimerThread* )pvArgToCompletionRoutine;
	if (a==4)
	{
		ctt->_bRunning = false;
	}
	std::cout << a<< "dio:"<< ctt->name.c_str() << std::endl;

}


int main()
{
	    string li = "name";
		string job_id = "w5";
		cTimerThread timer_;
		timer_.job_id = job_id;
		timer_.name = li;
		void *lpParam = NULL;
		timer_.CreateTimer(1000, TimerAPCRoutine, lpParam);
	return 0;
}


int cTimerThread::CreateTimer(unsigned int interval, PTIMERAPCROUTINE func, void* lpParam) 
{
	_nInterval = interval;
	_callbackFunc = func;
	_lpParam = lpParam;
	_bRunning = true;
	std::thread t1(timerThread,this);
	t1.join();//线程执行完自动退出
	return 0;
   }

DWORD WINAPI cTimerThread::timerThread(LPVOID lpParam) {
	cTimerThread* pThis = (cTimerThread*)lpParam;
	HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);

	LARGE_INTEGER li;

	li.QuadPart = 0;


	if (!SetWaitableTimer(hTimer, &li, pThis->_nInterval, pThis->_callbackFunc, pThis, FALSE))

	{

		CloseHandle(hTimer);

		return 0;

	}


	do
	{
		SleepEx(pThis->_nInterval, TRUE);

	} while (pThis->_bRunning);
	CloseHandle(hTimer);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值