CodeTheRobot

C++ Advanced · Lesson 09 of 23

Timers and periodic tasks

Fixed-rate loops with steady_clock and sleep_until, without drift.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain timers and periodic tasks in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A periodic task runs at a fixed rate, such as 50 Hz (every 20 ms). Do not sleep for 20 ms after each run, because the work time is added and the loop drifts. Instead compute the next deadline from the previous deadline and sleep_until it.

Measure how late each cycle actually starts; that jitter tells you whether the rate is realistic. A ROS 2 timer does this for you: you give it a period and a callback, and the executor calls the callback each time.

Guided lesson

Work through these steps

  1. 1.

    Read the timers and periodic tasks example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

using clock = std::chrono::steady_clock;
// A monotonic clock that never goes backwards.
constexpr auto period = std::chrono::milliseconds(20);
// 50 Hz.
auto next = clock::now() + period;
// The first deadline.
for (int i = 0; i < 5; ++i) {
// Run five cycles.
  tick(i);
// The task to run each cycle.
  std::this_thread::sleep_until(next);
// Sleep until the absolute deadline, not for a fixed time.
  const auto late = clock::now() - next;
// How far past the deadline we woke up.
  next += period;
// Advance the schedule from the previous deadline, so errors do not accumulate.
  std::cout << std::chrono::duration_cast<std::chrono::microseconds>(late).count() << " us late\n";
// Report the wake-up delay in microseconds.
}
// End of the loop.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

/topicpublishersubscribersubscribermessages delivered: 0MESSAGES BETWEEN NODES

Demo for Timers and periodic tasks. Expected result: ticks 5 true

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <chrono>
#include <iostream>
#include <thread>

int main() {
  using clock = std::chrono::steady_clock;
  using namespace std::chrono_literals;
  constexpr auto period = 20ms;
  const auto start = clock::now();
  auto next = start + period;
  int ticks = 0;
  for (int i = 0; i < 5; ++i) {
    ++ticks;  // the periodic task would run here
    // TODO: sleep until the absolute deadline next, then advance next by period
  }
  std::cout << "ticks " << ticks << '\n' << std::boolalpha << (clock::now() - start >= 100ms) << '\n';
  return 0;
}

Expected output

ticks 5
true
Stuck? Show the full solution (try it yourself first)
#include <chrono>
#include <iostream>
#include <thread>

int main() {
  using clock = std::chrono::steady_clock;
  using namespace std::chrono_literals;
  constexpr auto period = 20ms;
  const auto start = clock::now();
  auto next = start + period;
  int ticks = 0;
  for (int i = 0; i < 5; ++i) {
    ++ticks;  // the periodic task would run here
    std::this_thread::sleep_until(next);
    next += period;
  }
  std::cout << "ticks " << ticks << '\n' << std::boolalpha << (clock::now() - start >= 100ms) << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Run a 100 Hz loop for 10 seconds, store each cycle's lateness, and print the worst and average value after the loop (not inside it). Then replace sleep_until with sleep_for(period) and compare the total elapsed time.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.