c11 定时器

原创
2018/06/04 23:22
阅读数 661
#ifndef MINGHAI_BASE_DEADLINE_TIMER_H
#define MINGHAI_BASE_DEADLINE_TIMER_H

#if defined (_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include "minghai/minghai_global.h"
#include <thread>
#include <chrono>
#include <functional>
#include <cassert>
namespace minghai
{
	namespace base {
		class deadline_timer
		{
			typedef std::function<void()> function_type;
		public:
			deadline_timer() {}
			~deadline_timer() {}
			template<typename callable, class... arguments>
			void AsyncWait(int after, callable&& f, arguments&&... args) {				
				std::function<typename std::result_of<callable(arguments...)>::type()> task
				(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

				std::thread([after, task]() {
					assert(nullptr != task);
					std::this_thread::sleep_for(std::chrono::milliseconds(after));
					task();
				}).detach();
			}
			void AsyncWait(int after, const function_type &func) {				
				std::thread([after, func]() {
					assert(nullptr != func);
					std::this_thread::sleep_for(std::chrono::milliseconds(after));
					func();
				}).detach();
			}
			template<typename callable, class... arguments>
			void SyncWait(int after, callable&& f, arguments&&... args) {
				std::function<typename std::result_of<callable(arguments...)>::type()> task
				(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
				std::this_thread::sleep_for(std::chrono::milliseconds(after));
				assert(nullptr != task);
				task();
			}
			void SyncWait(int after, const function_type &func) {
				assert(func != nullptr);
				std::this_thread::sleep_for(std::chrono::milliseconds(after));
				func();
			}

		};
	}
}

#endif  // MINGHAI_BASE_DEADLINE_TIMER_H

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部