diff --git a/example/main.cpp b/example/main.cpp index aa04160..9972741 100644 --- a/example/main.cpp +++ b/example/main.cpp @@ -15,6 +15,8 @@ std::atomic_bool _shutDown; +#define TEST_IN_SUBTHREAD + #ifdef _WIN32 BOOL WINAPI ConsoleHandler(DWORD CtrlType) { switch (CtrlType) { @@ -144,6 +146,69 @@ void TestCronTimerInMainThread() { } } +#ifdef TEST_IN_SUBTHREAD +void TestCronTimerInSubThread() { + // 如果你想在子线程中触发定时器事件 + std::shared_ptr mgr = std::make_shared([&]() { + if (!mgr) + return; + while(!mgr->MultiThreadsReady()); + while (1) { + // 在子线程中触发定时器事件 + mgr->Update(); + } + }); + + mgr->AddTimer("* * * * * *", [](void) { + // 每秒钟都会执行一次 + Log("1 second cron timer hit"); + }); + + mgr->AddTimer("0/3 * * * * *", [](void) { + // 从0秒开始,每3秒钟执行一次 + Log("3 second cron timer hit"); + }); + + mgr->AddTimer("0 * * * * *", [](void) { + // 1分钟执行一次(每次都在0秒的时候执行)的定时器 + Log("1 minute cron timer hit"); + }); + + mgr->AddTimer("15;30;33 * * * * *", [](void) { + // 指定时间(15秒、30秒和33秒)点都会执行一次 + Log("cron timer hit at 15s or 30s or 33s"); + }); + + mgr->AddTimer("40-50 * * * * *", [](void) { + // 指定时间段(40到50内的每一秒)执行的定时器 + Log("cron timer hit between 40s to 50s"); + }); + + std::weak_ptr timer = mgr->AddDelayTimer(3000, [](void) { + // 3秒钟之后执行 + Log("3 second delay timer hit"); + }); + + // 可以在执行之前取消 + if (auto ptr = timer.lock(); ptr != nullptr) { + ptr->Cancel(); + } + + mgr->AddDelayTimer( + 10000, + [](void) { + // 每10秒钟执行一次,总共执行3次 + Log("10 second delay timer hit"); + }, + 3); + mgr->MarkMultiThreadsReady(true); + Log("10 second delay timer added"); + while (!_shutDown) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} +#endif + int main() { #ifdef _WIN32 SetConsoleCtrlHandler(ConsoleHandler, TRUE); @@ -153,6 +218,10 @@ int main() { #endif TestSplitStr(); +#ifndef TEST_IN_SUBTHREAD TestCronTimerInMainThread(); +#else + TestCronTimerInSubThread(); +#endif return 0; } diff --git a/include/cron_timer.h b/include/cron_timer.h index 5977190..5bc5592 100644 --- a/include/cron_timer.h +++ b/include/cron_timer.h @@ -424,6 +424,10 @@ class TimerMgr { public: TimerMgr() {} + TimerMgr(FUNC_CALLBACK&& func){ + std::thread subthread(func); + subthread.detach(); + } TimerMgr(const TimerMgr&) = delete; const TimerMgr& operator=(const TimerMgr&) = delete; @@ -513,6 +517,14 @@ class TimerMgr { return count; } + void MarkMultiThreadsReady(bool ready = false) { + multi_threads_ready_ = ready; + } + + bool MultiThreadsReady() + { + return multi_threads_ready_; + } private: void insert(const TimerPtr& p) { assert(!p->GetIsInList()); @@ -555,6 +567,7 @@ class TimerMgr { private: std::map> timers_; bool stopped_ = false; + bool multi_threads_ready_ = false; }; void BaseTimer::Cancel() {