cmake_minimum_required(VERSION 3.12)
project(time)
set(CMAKE_CXX_STANDARD 14)
add_executable(time main.cpp timer.cpp timer.h)
target_link_libraries(time X11 Xss pthread)
#include <iostream>
#include <X11/extensions/scrnsaver.h>
#include "timer.h"
#include <unistd.h>
int main() {
Display *display = XOpenDisplay(nullptr);
if(!display) {
std::cout << "XOpenDisplay ERROR.\n";
return 0;
}
XScreenSaverInfo *info = XScreenSaverAllocInfo();
Timer timer;
timer.start(500,[display, info](){
XScreenSaverQueryInfo(display, DefaultRootWindow(display), info);
std::cout << "idle: " << info->idle << std::endl;
});
usleep(1000000000);
XFree(info);
return 0;
}
#include "timer.h"
Timer::Timer() : _execute(false) {}
Timer::~Timer() {
if(_execute.load(std::memory_order_acquire)) {
stop();
}
}
void Timer::stop() {
_execute.store(false, std::memory_order_release);
if(_thd.joinable()) {
_thd.join();
}
}
void Timer::start(int _interval, std::function<void(void)> _function) {
if(_execute.load(std::memory_order_acquire)) {
stop();
}
_execute.store(true, std::memory_order_release);
_thd = std::thread([this, _interval, _function](){
while (_execute.load(std::memory_order_acquire)) {
_function();
std::this_thread::sleep_for(std::chrono::milliseconds(_interval));
}
});
}
bool Timer::isRunning() const {
return (_execute.load(std::memory_order_acquire) && _thd.joinable());
}
#ifndef TIME_TIMER_H
#define TIME_TIMER_H
#include <functional>
#include <atomic>
#include <thread>
class Timer {
public:
Timer();
~Timer();
void stop();
void start(int _interval, std::function<void(void)> _function);
bool isRunning() const;
private:
std::atomic<bool> _execute;
std::thread _thd;
};
#endif //TIME_TIMER_H