C++11标准stl库的timer
timer定时器,多线程,回调为阻塞模式。支持参数绑定,非常好使。
用法:
////////////////////////////////////////////////////////////////////////// //以下是测试代码 namespace timertester { class timertestclass { public: timertestclass(){}; ~timertestclass(){}; void testfn() { printf("timer callback is class func.\n"); FTimerEvent mTimer(3000, &timertestclass::threadfn, this); for (int i = 0; i < 5; i++) { printf("press any key to ...\n"); getchar(); mTimer.SetTimerEvent(); } printf("stop timer \n"); mTimer.StopTimer(); } void threadf(int i) { printf("test f i:%d\n", i); } void threadfn() { printf("test fn d\n"); } void threadfn2() { printf("test fn2222 \n"); } }; static void testfn1(timertestclass *cls) { cls->threadfn(); } static void testpf() { printf("test printf \n"); printf("callback ret. \n"); } static void prt(int& i) { printf("print %d\n", i); } static void timertest() { int t = 0; FTimerEvent timerstdref(1000, prt, std::ref(t)); for (int i = 0; i < 10; i++) { t = i; Sleep(1000); } timerstdref.StopTimer(); { printf("timer 0 manual to set\n"); //如果定时为0,则每次为手动触发 FTimerEvent timerman(0, [](){ printf("timerman in.\n"); Sleep(5000); printf("timerman out.\n"); }); timerman.SetTimerEvent(); timerman.SetTimerEvent(); timerman.StopTimer(); } printf("stop timer in callback\n"); FTimerEvent timer4; timer4.InitTimer(1000, [](FTimerEvent *pTimer){ printf("exit timer\n"); pTimer->StopTimer(); }, &timer4); Sleep(3000); timer4.StopTimer(); printf("set timer in callback\n"); FTimerEvent timer5; timer5.InitTimer(2000, [](FTimerEvent *pTimer){ static bool set = false; printf("timer in\n"); if (!set) { printf("set timer\n"); pTimer->SetTimerEvent(); set = true; } printf("timer out\n"); }, &timer5); Sleep(10000); timer5.StopTimer(); timertestclass test1; test1.testfn(); int x = 0; FTimerEvent timerref(1000, [&x]() { printf("x: %d \n", x); }); for (int i = 0; i < 10; i++) { x = i; Sleep(1000); } timerref.StopTimer(); FTimerEvent timerx(1000, [&test1]() { test1.threadfn2(); }); Sleep(10000); timerx.StopTimer(); FTimerEvent timer0(1000, testpf); Sleep(10000); timer0.StopTimer(); FTimerEvent timer1(1000, testfn1, &test1); Sleep(10000); timer1.StopTimer(); FTimerEvent timer2(1000, [](){ printf("lambada no param \n"); }); Sleep(10000); timer2.StopTimer(); int param = 0; FTimerEvent timer3(1000, [](int *p){ printf("lambada with param: %d \n", *p); }, ¶m); Sleep(10000); timer3.StopTimer(); } }
blackfeather 2020/9/7 ℃ 0评论