#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