c++定时器
问题描述
- 精选答案
-
#ifndef CTimer_hpp
#define CTimer_hpp
#include <stdio.h>
#include <functional>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
#include <string>
#include <condition_variable>
class CTimer
{
public:
CTimer(const std::string sTimerName =
"
"); //构造定时器,附带名称
~CTimer();
bool Start(unsigned int msTime, std::function<void()> task, bool bLoop = false, bool async = true);
void Cancel();
template<typename callable, typename... arguments>
bool SyncOnce(int msTime, callable&& fun, arguments&&... args) {
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...)); //绑定任务函数或lambda成function
return Start(msTime, task, false, false);
}
template<typename callable, typename... arguments>
bool AsyncOnce(int msTime, callable&& fun, arguments&&... args) {
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));
return Start(msTime, task, false);
}
template<typename callable, typename... arguments>
bool AsyncOnce(callable&& fun, arguments&&... args) {
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));
return Start(1, task, false);
}
template<typename callable, typename... arguments>
bool AsyncLoop(int msTime, callable&& fun, arguments&&... args) {
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(fun), std::forward<arguments>(args)...));
return Start(msTime, task, true);
}
private:
void DeleteThread();//删除任务线程
public:
int m_nCount = 0; //循环次数
private:
std::string m_sName; //定时器名称
std::atomic_bool m_bExpired; //装载的任务是否已经过期
std::atomic_bool m_bTryExpired;//装备让已装载的任务过期(标记)
std::atomic_bool m_bLoop;//是否循环
std::thread *m_Thread = nullptr;
std::mutex m_ThreadLock;
std::condition_variable_any m_ThreadCon;
};
猜你喜欢内容
-
简单网:构建全网教育数据枢纽,让知识检索化繁为...
简单网:构建全网教育数据枢纽,让知识检索化繁为“简”回答数有0条优质答案参考
-
去三亚有什么好玩的地方
去三亚有什么好玩的地方回答数有1条优质答案参考
-
石狮一日游必去景点推荐
石狮一日游必去景点推荐回答数有1条优质答案参考
-
电气工程师的证书考取条件是什么
电气工程师的证书考取条件是什么回答数有1条优质答案参考
-
房地产估价师的具体报考条件有啥
房地产估价师的具体报考条件有啥回答数有1条优质答案参考
-
房产经纪人的工作内容具体包含什么
房产经纪人的工作内容具体包含什么回答数有1条优质答案参考
-
学习小提琴都有哪些难点
学习小提琴都有哪些难点回答数有1条优质答案参考
-
企业行政管理证书的含金量怎么样
企业行政管理证书的含金量怎么样回答数有1条优质答案参考
-
初学者要怎么入门小提琴
初学者要怎么入门小提琴回答数有1条优质答案参考
-
报考珠宝鉴定师要啥条件
报考珠宝鉴定师要啥条件回答数有1条优质答案参考
















