利用boost实现定时器

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
using namespace std::chrono;
using namespace boost::posix_time;
using namespace boost::gregorian;
using namespace std::placeholders;

typedef function time_func_type;

class ExcuteTimer
{
public:
	ExcuteTimer(boost::asio::io_service &io):m_timer(io){}
	~ExcuteTimer(){ m_timer.cancel();}

	time_t local_now_tm()
	{
		return time(0);
	}

	char* time_t2str(time_t timestamp, char* timestr, int len)
	{
		struct tm *ptm;
		ptm = localtime(×tamp);
		strftime(timestr, len, "%Y-%m-%d %H:%M:%S", ptm);
		cout << timestr << endl;
		return timestr;
	}

	time_t str2time_t(const char *timestr)
	{
		struct tm ptm;
		strptime(timestr, "%Y-%m-%d %H:%M:%S", &ptm);
		time_t t = mktime(&ptm);
		return t;
	}

	void runAt(time_t timestamp, time_func_type callback)
	{
		int seconds = timestamp - time(0);
		if(seconds <0) return;
		m_timer.expires_at(chrono::steady_clock::now() + chrono::seconds(seconds));
		m_timer.async_wait(std::bind(callback, 1, timestamp));
	}
	void runAt(std::string date, time_func_type callback)
	{
		time_t t = str2time_t(date.c_str());
		time_t now = time(0);
		if(t < now)
			return;
		int seconds = t-now;
		m_timer.expires_from_now(chrono::seconds(seconds));
		m_timer.async_wait(std::bind(callback, 2, t));
	}
	void runAfter(int seconds, time_func_type callback)
	{
		m_timer.expires_from_now(std::chrono::seconds(seconds));
		m_timer.async_wait(std::bind(callback, 3, time(0)+seconds));
	}

	void runCircle(int seconds, time_func_type callback)
	{
		cout << "circle" << endl;
		callback(1, time(0));
		m_timer.expires_from_now(std::chrono::seconds(seconds));
		m_timer.async_wait(std::bind(&ExcuteTimer::runCircle, this, seconds,callback));
	}
private:
	boost::asio::steady_timer m_timer;
};


void testPrint(int id, time_t tm)
{
	cout << "id==="< g_excuteTimerManager;

int main(int argc, char const *argv[])
{
	g_excuteTimerManager.reset(new ExcuteTimerManager());
	boost::asio::io_service& io = g_excuteTimerManager->get_io();
	ExcuteTimer timer(io);
	ExcuteTimer timer2(io);
	ExcuteTimer timer3(io);
	TestF testf;
	time_func_type func = std::bind(&TestF::print, &testf, _1);
	// timer.runAt(time(0)+10, func);
	// timer2.runAt(time(0), func);
	timer3.runCircle(5, func);
	//timer.runAt(time(0)+5, testPrint);
	//timer.runAt(std::string("2019-1-1 10:20:00"), testPrint);
	//timer.runAfter(10, func);
	g_excuteTimerManager->run();

	while(1);
	return 0;
}

//g++ timer.cpp --std=c++11 -pthread -lboost_system -lboost_date_time

 

你可能感兴趣的:(c/c++)