Skip to content

05. Shedulling

ogoun edited this page Apr 23, 2026 · 3 revisions

Scheduling

Sheduller (kept with the historical spelling) is a single-threaded, fiber-based scheduler. It uses one system timer per instance, so densely-scheduled tasks stay cheap.

The default scheduler is a process-wide singleton (Sheduller.* static methods). Need isolation? Call Sheduller.Create() for a fresh instance.

One-off invocations

After a delay

Sheduller.RemindAfter(TimeSpan.FromSeconds(2),
    () => Console.WriteLine("Fired!"));

Sheduller.RemindAfter(TimeSpan.FromSeconds(5),
    taskId => Console.WriteLine($"Task {taskId} fired"));

At a specific time

Sheduller.RemindAt(DateTime.Now.AddSeconds(5),
    () => Console.WriteLine(DateTime.Now.ToLongTimeString()));

Sheduller.RemindAt(DateTime.Now.AddSeconds(10),
    taskId => Console.WriteLine($"[{taskId}]: {DateTime.Now:T}"));

Repeating tasks

Fixed period

// first tick after 10s, then every 5s
var taskId = Sheduller.RemindEvery(
    TimeSpan.FromSeconds(10),
    TimeSpan.FromSeconds(5),
    id => Console.WriteLine($"Repeating task {id}"));

// cancel after one minute
Sheduller.RemindAt(DateTime.Now.AddMinutes(1),
    () => Sheduller.Remove(taskId));

While a condition holds

Sheduller.RemindWhile(TimeSpan.FromSeconds(1), () =>
{
    Console.WriteLine("tick");
    return DateTime.Now.Ticks % 7 == 0;   // false → stop
});

Adaptive period

int period = 10;
Sheduller.RemindEveryNonlinearPeriod(
    () =>                                   // pick next interval
    {
        if (period > 1) period /= 2;
        return TimeSpan.FromSeconds(period);
    },
    () => Console.WriteLine("adaptive tick"));

Adaptive date

Sheduller.RemindEveryNonlinearDate(
    last => last.AddSeconds(1),             // compute next fire time
    () => Console.WriteLine("date-driven tick"));

Control surface

Sheduller.Remove(taskId);   // cancel one task

Sheduller.Pause();          // stop firing, keep tasks registered
Sheduller.Resume();

Sheduller.Clean();          // drop every task
Sheduller.Dispose();        // shut down the default scheduler

Every register method returns a long task id that identifies the task for later Remove.

Multiple schedulers

Create an isolated scheduler when you have a high tick density (e.g. a financial engine with thousands of micro-events):

var s = Sheduller.Create();

s.RemindEvery(TimeSpan.FromMilliseconds(50), () => Tick());

One scheduler = one system timer. Splitting very busy workloads across multiple schedulers can reduce timer-wheel contention.

Practical patterns

  • Timeouts. Sheduller.RemindAfter(timeout, () => cts.Cancel()); — cheaper than spinning a Task.Delay.
  • Health pings. Sheduller.RemindEvery(interval, interval, () => Ping());
  • Backoff retries. RemindEveryNonlinearPeriod with an exponential backoff lambda.
  • Cron-like jobs. Compose RemindEveryNonlinearDate with your own cron evaluator.

Clone this wiki locally