Try Embedded

Write your own cooperative scheduler (no library)

A table of tasks run on time from loop(), in plain C with no library, and a measurement of its weak spot: one slow task delays all the others.

RTOS · Intermediate

In a real product: Appliance controller (Consumer electronics): A simple scheduler runs the appliance's jobs on time.

Before reaching for an RTOS, it helps to see the simplest scheduler there is. Here three jobs run on their own periods from a task table and a short loop: no library, no interrupts, no assembly. Many real products, from thermostats to remote controls, work exactly like this. The sketch also measures how late each task starts, which shows where this design stops working.

What you'll learn

  • What a scheduler is: the code that decides what runs next
  • A task table: a function, a period and the next due time for each task
  • Rollover-safe timing with millis(), and scheduling from the due time so errors don't add up
  • Why a cooperative scheduler is only as fast as its slowest task, and what preemption adds

How it works

Each entry in tasks[] holds a task's name, its function, its period and when it is next due. loop() is the scheduler: on every pass it checks each task, and if one is due it notes how late it is, moves its due time on by one period, and calls it.

Three details matter:

  • (long)(now - t.dueAt) >= 0 compares times by subtracting them. That stays correct when millis() rolls over after about 49 days; now >= t.dueAt would not.
  • t.dueAt += t.periodMs, not t.dueAt = now + t.periodMs. Scheduling from the due time keeps a 250 ms task at exactly 4 runs a second over the long term, even when one run starts a little late.
  • Each task runs to completion. Nothing can interrupt it to run another task. That is what cooperative means: each task has to give the CPU back quickly, by returning.

The report task prints the worst lateness of every task, once a second. With these short tasks it stays at 0 ms.

The sketch also writes the name of each task it starts to three spare registers (GPIOR0 to GPIOR2), which the simulator's Tasks panel reads. idle is the time loop() spends finding nothing due.

The weak spot

Add delay(300); at the end of blinkGreen() and run it again. The report now says red=250: the red LED's task waited a quarter of a second behind the slow green task, and its blinking turns uneven. A task that is late "catches up" by running twice in quick succession, because its due time was already in the past.

In a cooperative scheduler, every task's worst-case delay is the sum of the longest runs of the others. The fixes are to split slow work into short steps (a state machine that does a little on each call), or to let a timer interrupt take the CPU away from a task that runs too long: preemption, which is what an RTOS kernel adds. The next project builds one.

Try this

  • Add the delay(300) described above and watch the lateness and the Tasks panel.
  • Rewrite the slow task as a state machine: instead of delay(300), return at once and finish the work on a later call, when 300 ms have passed. The lateness goes back to 0.
  • Give each task a priority, and when several are due in the same pass, run the highest first.
  • Count how many passes loop() makes per second. That number is your scheduler's resolution.

sketch.ino

// A cooperative scheduler with no library: a table of tasks, each a function that does a little work and returns,
// called from loop() when its period comes round. It measures how late each task ran.

struct Task {
  const char *name;
  void (*run)();
  unsigned long periodMs;
  unsigned long dueAt;      // when it should run next
  unsigned long worstLate;  // the latest it has started, in ms after it was due
};

// Tells the simulator's Tasks panel what runs now (two spare registers hold the name's address; GPIOR0 says "switch").
void trace(const char *name) {
  GPIOR1 = (uint16_t)name & 0xff;
  GPIOR2 = (uint16_t)name >> 8;
  GPIOR0 = 1;
}

const int RED = 12;
const int GREEN = 11;

void blinkRed()   { digitalWrite(RED, !digitalRead(RED)); }
void blinkGreen() { digitalWrite(GREEN, !digitalRead(GREEN)); }
void report();

Task tasks[] = {
  { "red",    blinkRed,   250,  0, 0 },
  { "green",  blinkGreen, 700,  0, 0 },
  { "report", report,     1000, 0, 0 },
};
const int TASK_COUNT = sizeof(tasks) / sizeof(tasks[0]);

void report() {
  Serial.print(F("at "));
  Serial.print(millis());
  Serial.print(F(" ms, worst lateness:"));
  for (Task &t : tasks) {
    Serial.print(' ');
    Serial.print(t.name);
    Serial.print('=');
    Serial.print(t.worstLate);
  }
  Serial.println(F(" ms"));
}

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  Serial.begin(9600);
  unsigned long now = millis();
  for (Task &t : tasks) t.dueAt = now;
  trace("idle");
}

// The scheduler. Each pass runs every task that is due, in table order; a task runs to completion before the next.
void loop() {
  unsigned long now = millis();
  for (Task &t : tasks) {
    if ((long)(now - t.dueAt) >= 0) {
      unsigned long late = now - t.dueAt;
      if (late > t.worstLate) t.worstLate = late;
      t.dueAt += t.periodMs;  // from when it was due, not from now, so lateness does not add up
      trace(t.name);
      t.run();
      trace("idle");
    }
  }
}

Lessons behind it