// Test.cpp : 定义控制台应用程序的入口点。
//
#include "../I_Timer.H"#include <boost/thread.hpp>
void onTimer1()
{
std::cout << "onTimer1,it should pass 1 s!" << std::endl;
}void onTimer2()
{
std::cout << "onTimer2,it should pass 2 s!*****" << std::endl;
}void onTimer_chen()
{
std::cout << "onTimer_chen,it should pass 3 s!***************" << std::endl;
}int main(int argc, char* argv[])
{I_TimerFactory* tf = NEW(TimerFactory);
// auto tm01 = tf->createTimer();#if 1
auto myTimer1 = /*Timer::createTimer();*/tf->createTimer();
auto myTimer2 = /*Timer::createTimer();*/tf->createTimer();
auto myTimer_chen = /*Timer::createTimer();*/tf->createTimer();myTimer1->regTimer(boost::bind(onTimer1));
myTimer1->setInterval(1000);
myTimer1->start();myTimer2->regTimer(boost::bind(onTimer2));
myTimer2->setInterval(2000);
myTimer2->start();myTimer_chen->regTimer(boost::bind(onTimer_chen));
myTimer_chen->setInterval(3000);
myTimer_chen->start();//tf->driveTimer();
for (int i=0;i<10;++i)
{tf->driveTimer();
boost::this_thread::interruptible_wait(1000);
std::cout<<1<<std::endl;
}std::cout << "myTimer2 stop!" << std::endl;
std::cout << "***************" << std::endl;
getchar();
myTimer2->stop();for (int i=0;i<100;++i)
{
tf->driveTimer();
boost::this_thread::interruptible_wait(100);
}// 析构会反注册
myTimer2 = tf->createTimer();
myTimer2->regTimer(boost::bind(onTimer2));
myTimer2->setInterval(2000);
myTimer2->start();
getchar();
std::cout << std::endl << "123456897*" << std::endl;
#if 0
// 也可以移入其他线程驱动
// 不推荐,非线程安全
boost::thread thrd([](){std::cout << "other thread drive!" << std::endl;
for (int i=0;i<100;++i)
{
tf->driveTimer();
boost::this_thread::interruptible_wait(100);
}
});
#endif
// thrd.join();
#endif
std::cout << std::endl << "---------------------*" << std::endl;
return 0;
}
一直搞不懂这个定时器怎么用的,正好程序里面有个例子,实验了一下
主要是这个drive(),这个定时器需要自己调用drive驱动
tf->driveTimer();
boost::this_thread::interruptible_wait(100);
interruptible_wait表示等待100ms,如果时间是100ms,就没有定时器到时间,1000ms则每次myTimer1总会执行,myTimer2,myTimer2则不一定,2000ms则myTimer1,myTimer2则每次执行,
myTimer3不一定,3000ms则三个定时器都会执行,看这个wait时间的多少。时间少了就没有定时器执行,多了则都会执行。具体程序中用,还需研究。
定时器(了解),布布扣,bubuko.com