Libftpp
A modern C++ library
PersistentWorker Class Reference

Persistent worker thread that executes tasks in a continuous loop. More...

#include <persistent_worker.hpp>

Public Member Functions

 PersistentWorker ()
 
 ~PersistentWorker ()
 
void addTask (const std::string &name, const std::function< void()> &jobToExecute)
 
void removeTask (const std::string &name)
 

Detailed Description

Persistent worker thread that executes tasks in a continuous loop.

This class provides a background worker thread that continuously executes registered tasks in a loop. Tasks can be dynamically added and removed during runtime, making it ideal for background processing, periodic operations, or event-driven task execution. The worker uses condition variables for efficient thread synchronization and CPU usage.

Note
Allows dynamic addition/removal of tasks during runtime
Supports configurable pause between each task execution (PAUSE_BT_TASK in milliseconds)

Thread-safe task management using mutex and condition variables

Automatically starts worker thread on construction and stops on destruction

Worker thread sleeps when no tasks are available, reducing CPU usage

// Create worker (automatically starts background thread)
// Add tasks that will run continuously
worker.addTask("logger", []() {
std::cout << "Log entry at " << getCurrentTime() << std::endl;
});
worker.addTask("cleanup", []() {
cleanupTempFiles();
});
worker.addTask("heartbeat", []() {
sendHeartbeat();
});
// Tasks now run continuously in background...
// Do other work...
// Remove specific task
worker.removeTask("cleanup");
// Worker stops automatically when destroyed
Persistent worker thread that executes tasks in a continuous loop.
void removeTask(const std::string &name)
void addTask(const std::string &name, const std::function< void()> &jobToExecute)
Warning
Tasks should be lightweight to avoid blocking other tasks in the loop
Note
Task execution order is not guaranteed due to unordered_map usage

Definition at line 57 of file persistent_worker.hpp.

Constructor & Destructor Documentation

◆ PersistentWorker()

PersistentWorker::PersistentWorker ( )

Definition at line 3 of file persistent_worker.cpp.

◆ ~PersistentWorker()

PersistentWorker::~PersistentWorker ( )

Definition at line 8 of file persistent_worker.cpp.

Member Function Documentation

◆ addTask()

void PersistentWorker::addTask ( const std::string &  name,
const std::function< void()> &  jobToExecute 
)

Definition at line 19 of file persistent_worker.cpp.

◆ removeTask()

void PersistentWorker::removeTask ( const std::string &  name)

Definition at line 26 of file persistent_worker.cpp.