10 #include <spdlog/spdlog.h>
22 int64_t measured_interval = 0;
29 std::atomic<bool> g_stop_sched = {
false};
33 void highPriorityTask()
35 static unsigned int loop_counter = 0;
38 static std::chrono::high_resolution_clock::time_point tic;
42 auto toc = std::chrono::high_resolution_clock::now();
45 auto measured_interval
46 = std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count();
50 std::lock_guard<std::mutex> lock(g_mutex);
51 g_data.measured_interval = measured_interval;
55 if (++loop_counter > 5000) {
61 tic = std::chrono::high_resolution_clock::now();
63 }
catch (
const std::exception& e) {
64 spdlog::error(e.what());
70 void lowPriorityTask()
72 static uint64_t accumulated_time = 0;
73 static uint64_t num_measures = 0;
74 static float avg_interval = 0.0;
75 int measured_interval = 0;
79 std::lock_guard<std::mutex> lock(g_mutex);
80 measured_interval = g_data.measured_interval;
84 accumulated_time += measured_interval;
86 avg_interval = (float)accumulated_time / (
float)num_measures;
90 "High-priority task interval (curr | avg) = {} | {} us", measured_interval, avg_interval);
96 std::cout <<
"Required arguments: None" << std::endl;
97 std::cout <<
"Optional arguments: None" << std::endl;
98 std::cout << std::endl;
102 int main(
int argc,
char* argv[])
106 if (flexiv::rdk::utility::ProgramArgsExistAny(argc, argv, {
"-h",
"--help"})) {
116 scheduler.
AddTask(std::bind(highPriorityTask),
"HP periodic", 1, scheduler.
max_priority());
118 scheduler.
AddTask(std::bind(lowPriorityTask),
"LP periodic", 1000, 0);
123 while (!g_stop_sched) {
124 std::this_thread::sleep_for(std::chrono::milliseconds(1));
130 spdlog::warn(
"Scheduler will restart in 2 seconds");
131 std::this_thread::sleep_for(std::chrono::seconds(2));
132 g_stop_sched =
false;
136 while (!g_stop_sched) {
137 std::this_thread::sleep_for(std::chrono::milliseconds(1));
142 }
catch (
const std::exception& e) {
143 spdlog::error(e.what());
Real-time scheduler that can simultaneously run multiple periodic tasks. Parameters for each task are...
int max_priority() const
[Non-blocking] Get maximum available priority for user tasks.
void AddTask(std::function< void(void)> &&callback, const std::string &task_name, int interval, int priority, int cpu_affinity=-1)
[Non-blocking] Add a new periodic task to the scheduler's task pool. Each task in the pool is assigne...
void Stop()
[Blocking] Stop all added tasks. The periodic execution will stop and all task threads will be closed...
void Start()
[Blocking] Start all added tasks. A dedicated thread will be created for each added task and the peri...