123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- #include <chrono>
- #include <functional>
- #include <list>
- #include <mutex>
- #include <thread>
- #include <vector>
- #include <iostream>
- #include "ThreadPool.h"
- #include "spdlog/spdlog.h"
- #include "RingQueue.hpp"
- using TaskFunc = std::function<void()>;
- struct Task {
- bool is_loop;
- TaskFunc func;
- long interval;
- };
- class TimerWheel {
- public:
-
-
- explicit TimerWheel()
- : m_current_index(0) {
- m_wheel_size = 1000 * 60 * 60;
- m_interval_ms = 1000;
- m_firstLevelWheel.resize(1000);
- m_secondLevelWheel.resize(60);
- m_thirdLevelWheel.resize(60);
- }
- ~TimerWheel() {
- Stop();
- }
-
- void Start() {
- if (m_running) {
- return;
- }
- m_running = true;
-
- m_thread = std::thread([this]() {
- while (m_running) {
- std::this_thread::sleep_for(std::chrono::milliseconds(m_interval_ms));
- Tick();
- }
- std::cout << "timer oooops!" << std::endl;
- });
- m_thread.detach();
- }
- void Stop() {
- if (!m_running) {
- return;
- }
- m_running = false;
- if (m_thread.joinable()) {
- m_thread.join();
- }
- }
-
- void AddTask(int timeout_ms, Task task, bool is_loop = false) {
- std::lock_guard<std::mutex> lock(mutex_);
-
- size_t ticks = timeout_ms / m_interval_ms;
-
- size_t index = (m_current_index + ticks) % m_wheel_size;
-
- size_t allindex = index;
- for (size_t i = 1 ; allindex < m_wheel_size; i++)
- {
- allindex = index * i;
- if (allindex >= m_wheel_size)
- break;
- wheel_[allindex].push_back(task);
- }
-
- }
- private:
-
- void Tick() {
- std::lock_guard<std::mutex> lock(mutex_);
-
- auto& tasks = wheel_[m_current_index];
- for (const auto& task : tasks) {
- task();
- }
-
-
- m_current_index = (m_current_index + 1) % m_wheel_size;
- }
- private:
- long m_max_interval = 0;
- size_t m_wheel_size;
- int m_interval_ms;
- long m_firstLevelCount;
- long m_secondLevelCount;
- long m_thirdLevelCount;
- std::vector<std::list<Task>> m_firstLevelWheel;
- std::vector<std::list<Task>> m_secondLevelWheel;
- std::vector<std::list<Task>> m_thirdLevelWheel;
- size_t m_current_index;
- bool m_running = false;
- std::thread m_thread;
- std::mutex mutex_;
-
- };
|