Program Listing for File EventTimerHandle.cpp

Return to documentation for file (EventLoop/EventTimerHandle.cpp)

#include "netio3-backend/EventLoop/EventTimerHandle.hpp"

#include "netio3-backend/EventLoop/BaseEventLoop.hpp"

netio3::EventTimerHandle::EventTimerHandle(const int fd,
                                           const std::shared_ptr<BaseEventLoop>& evloop) :
  m_fd{std::make_shared<int>(fd)}, m_evloop{evloop}
{}

netio3::EventTimerHandle::~EventTimerHandle()
{
  if (m_fd.use_count() > 1) {
    return;
  }
  if (auto spt = m_evloop.lock()) {
    stop();
    spt->remove_timer(*this);
  }
}

  void netio3::EventTimerHandle::stop()
{
  // Check if already closed
  if (fcntl(*m_fd, F_GETFD) == -1) {
    m_is_running = false;
    return;
  }
  const auto its = itimerspec{.it_interval = timespec{.tv_sec = 0, .tv_nsec = 0},
                              .it_value = timespec{.tv_sec = 0, .tv_nsec = 0}};
  if (timerfd_settime(*m_fd, 0, &its, nullptr) == -1) {
    ers::error(FailedSetTimer(ERS_HERE, *m_fd, utility::error_message(errno)));
  } else {
    m_is_running = false;
  }
}