Files
EchoionPlugin/include/echoion/plugin/FileWatcher.hpp
T
2026-02-01 23:07:06 +03:00

63 lines
1.5 KiB
C++

#pragma once
#include <functional>
#include <filesystem>
#include <thread>
#include <atomic>
#include <mutex>
#include <chrono>
namespace Echoion::Plugin {
/**
* @brief Simple file watcher that monitors a file for changes
* and triggers a callback when the file is modified.
*/
class FileWatcher {
public:
using ChangeCallback = std::function<void()>;
FileWatcher();
~FileWatcher();
// Disable copy
FileWatcher(const FileWatcher&) = delete;
FileWatcher& operator=(const FileWatcher&) = delete;
/**
* @brief Start watching a file for changes
* @param filePath Path to the file to watch
* @param callback Function to call when file changes
* @param intervalMs Polling interval in milliseconds
*/
void startWatching(
const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs = std::chrono::milliseconds(1000)
);
/**
* @brief Stop watching
*/
void stopWatching();
[[nodiscard]] bool isWatching() const noexcept;
private:
void watchLoop();
std::filesystem::path watchedPath_;
ChangeCallback callback_;
std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
std::atomic<bool> stopRequested_{false};
std::thread watchThread_;
std::mutex mutex_;
// Store last modification time
std::filesystem::file_time_type lastWriteTime_;
std::uintmax_t lastFileSize_ = 0;
};
} // namespace Echoion::Plugin