github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/util/timer_loop.h (about)

     1  // Copyright (C) 2017 go-nebulas authors
     2  //
     3  // This file is part of the go-nebulas library.
     4  //
     5  // the go-nebulas library is free software: you can redistribute it and/or
     6  // modify
     7  // it under the terms of the GNU General Public License as published by
     8  // the Free Software Foundation, either version 3 of the License, or
     9  // (at your option) any later version.
    10  //
    11  // the go-nebulas library is distributed in the hope that it will be useful,
    12  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  // GNU General Public License for more details.
    15  //
    16  // You should have received a copy of the GNU General Public License
    17  // along with the go-nebulas library.  If not, see
    18  // <http://www.gnu.org/licenses/>.
    19  //
    20  
    21  #pragma once
    22  #include "common/common.h"
    23  #include "core/command.h"
    24  #include <boost/asio.hpp>
    25  #include <boost/asio/deadline_timer.hpp>
    26  
    27  namespace neb {
    28  namespace util {
    29  
    30  class timer_loop {
    31  public:
    32    inline timer_loop(boost::asio::io_service *service)
    33        : m_service(service), m_exit_flag(false) {
    34      neb::core::command_queue::instance()
    35          .listen_command<neb::core::exit_command>(
    36              this, [this](const std::shared_ptr<neb::core::exit_command> &) {
    37                m_exit_flag = true;
    38              });
    39    }
    40  
    41    template <typename Func>
    42    void register_timer_and_callback(long seconds, Func &&f) {
    43  
    44      auto timer = std::make_unique<boost::asio::deadline_timer>(
    45          *m_service, boost::posix_time::seconds(seconds));
    46  
    47      m_timers.push_back(std::move(timer));
    48      std::unique_ptr<boost::asio::deadline_timer> &t = m_timers.back();
    49      auto pt = t.get();
    50  
    51      pt->async_wait([this, pt, seconds, f](const boost::system::error_code &ec) {
    52        timer_callback(ec, seconds, pt, f);
    53      });
    54    }
    55  
    56  protected:
    57    void timer_callback(const boost::system::error_code &ec, long seconds,
    58                        boost::asio::deadline_timer *timer,
    59                        std::function<void()> func);
    60  
    61  protected:
    62    boost::asio::io_service *m_service;
    63    std::atomic_bool m_exit_flag;
    64    std::vector<std::unique_ptr<boost::asio::deadline_timer>> m_timers;
    65  };
    66  } // namespace util
    67  } // namespace neb