working timer
This commit is contained in:
83
include/services/timerService.hpp
Normal file
83
include/services/timerService.hpp
Normal file
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "glibmm/main.h"
|
||||
#include "sigc++/signal.h"
|
||||
class TimerService {
|
||||
struct TimerData {
|
||||
uint64_t duration;
|
||||
uint64_t timerId;
|
||||
};
|
||||
|
||||
public:
|
||||
static std::shared_ptr<TimerService> getInstance() {
|
||||
if (!instance) {
|
||||
instance = std::make_shared<TimerService>();
|
||||
|
||||
// add a timer to tick every second
|
||||
Glib::signal_timeout().connect([]() {
|
||||
instance->tick();
|
||||
return true; // continue calling every second
|
||||
},
|
||||
1000);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
void addTimer(uint64_t duration) {
|
||||
this->timerAddedSignal.emit(std::to_string(duration), timerIdCounter);
|
||||
|
||||
this->activeTimers[timerIdCounter] = TimerData{.duration = duration, .timerId = timerIdCounter};
|
||||
|
||||
timerIdCounter++;
|
||||
}
|
||||
|
||||
void expireTimer(uint64_t timerId) {
|
||||
this->timerExpiredSignal.emit(timerId);
|
||||
}
|
||||
|
||||
void removeTimer(uint64_t timerId) {
|
||||
this->activeTimers.erase(timerId);
|
||||
this->timerCancelledSignal.emit(timerId);
|
||||
}
|
||||
|
||||
sigc::signal<void(const std::string &, u_int64_t)> &getSignalTimerSet() {
|
||||
return this->timerAddedSignal;
|
||||
}
|
||||
|
||||
sigc::signal<void(u_int64_t)> &getSignalTimerExpired() {
|
||||
return this->timerExpiredSignal;
|
||||
}
|
||||
|
||||
sigc::signal<void(u_int64_t)> &getSignalTimerCancelled() {
|
||||
return this->timerCancelledSignal;
|
||||
}
|
||||
|
||||
sigc::signal<void()> tickSignal;
|
||||
|
||||
private:
|
||||
static inline uint64_t timerIdCounter = 0;
|
||||
sigc::signal<void(const std::string &, u_int64_t)> timerAddedSignal;
|
||||
sigc::signal<void(u_int64_t)> timerCancelledSignal;
|
||||
sigc::signal<void(u_int64_t)> timerExpiredSignal;
|
||||
inline static std::shared_ptr<TimerService> instance = nullptr;
|
||||
|
||||
std::map<uint64_t, TimerData> activeTimers;
|
||||
|
||||
void tick() {
|
||||
for (auto &[id, timer] : activeTimers) {
|
||||
|
||||
if (timer.duration > 0) {
|
||||
timer.duration--;
|
||||
} else if (timer.duration == 0) {
|
||||
expireTimer(timer.timerId);
|
||||
timer.duration = -1; // Mark as expired to prevent multiple expirations
|
||||
}
|
||||
}
|
||||
|
||||
tickSignal.emit();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user