Browse Source

update

disinfection_machine
zhaohe 2 years ago
parent
commit
75c691900a
  1. 63
      core/components/timer/simple_timer.cpp
  2. 57
      core/components/timer/simple_timer.hpp
  3. 2
      module.cmake

63
core/components/timer/simple_timer.cpp

@ -0,0 +1,63 @@
#include "simple_timer.hpp"
using namespace std;
using namespace iflytop;
using namespace core;
void SimpleTimer::setTimeout(function<void()> function, int delay) {
lock_guard<mutex> lock(m_mutex);
if (m_thread) {
m_thread->join();
m_thread = nullptr;
}
m_thread.reset(new Thread(m_name, [=]() {
ThisThread thisThread;
zsteady_tp start = zsteady_clock().now();
while (!thisThread.getExitFlag()) {
if (zsteady_clock().elapsedTimeMs(start) >= delay) {
function();
break;
}
thisThread.sleepForMs(3);
}
}));
}
bool SimpleTimer::isRunning() {
lock_guard<mutex> lock(m_mutex);
if (m_thread) {
return !m_thread->isWaitingForJoin();
}
return false;
}
void SimpleTimer::stop() {
lock_guard<mutex> lock(m_mutex);
if (m_thread) {
m_thread->join();
m_thread = nullptr;
}
}
void SimpleTimer::setInterval(function<void()> function, int interval) {
lock_guard<mutex> lock(m_mutex);
if (m_thread) {
m_thread->join();
m_thread = nullptr;
}
m_thread.reset(new Thread(m_name, [=]() {
ThisThread thisThread;
zsteady_tp start = zsteady_clock().now();
while (!thisThread.getExitFlag()) {
if (zsteady_clock().elapsedTimeMs(start) >= interval) {
function();
start = zsteady_clock().now();
}
thisThread.sleepForMs(3);
}
}));
}

57
core/components/timer/simple_timer.hpp

@ -0,0 +1,57 @@
//
// Created by zwsd
//
#pragma once
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include "iflytopcpp/core/components/timeutils.hpp"
#include "iflytopcpp/core/spdlogfactory/logger.hpp"
#include "iflytopcpp/core/thread/thread.hpp"
/**
* @brief
*
* service: SimpleTimer
*
* :
* :
* :
* :
*
*/
namespace iflytop {
using namespace std;
using namespace core;
class SimpleTimer {
ENABLE_LOGGER(SimpleTimer);
unique_ptr<Thread> m_thread;
string m_name;
mutex m_mutex;
public:
SimpleTimer(string name) { m_name = name; };
void setTimeout(function<void()> func, int delay);
void setInterval(function<void()> func, int interval);
void stop();
bool isRunning();
~SimpleTimer() {
if (m_thread) m_thread->join();
};
};
} // namespace iflytop

2
module.cmake

@ -29,7 +29,7 @@ set(DEP_SRC
dep/iflytopcpp/core/components/process/process_unix.cpp
dep/iflytopcpp/core/components/process/process.cpp
dep/iflytopcpp/core/components/timer/simple_timer.cpp
#
)
set(DEP_DEFINE ${DEP_DEFINE})

Loading…
Cancel
Save