metronome/scheduler

Search:
Group by:

Metronome

Beaters delegate nominal calculation to private explicit-input helpers and retain jitter, waiting, throttling, lifecycle state, and job execution. The scheduler owns registered beaters and starts their execution loops.

Example usage::

import metronome/scheduler, times, asyncdispatch

metronome:
  every(seconds=1, id="tick", throttle=1, async=true):
    echo("async tick ", now())
    await sleepAsync(2000)
  every(seconds=1, id="sync tick", throttle=1):
    echo("sync tick ", now())

Types

Beater = ref object of RootObj
  case kind*: BeaterKind
  of bkInterval:
    interval*: TimeInterval
    jitter*: TimeInterval
  of bkCron:
    cron*: Cron
    timezone*: Option[Timezone]
  of bkCustom:
    nextRunProc*: NextRunProc
  of bkOnce:
    nil
Beater generates beats for the next runs.
BeaterAsyncProc = proc (): Future[void] {.closure.}
BeaterKind {.pure.} = enum
  bkInterval, bkCron, bkCustom, bkOnce
BeaterState {.pure.} = enum
  bsRunning, bsPaused, bsStopped
BeaterThreadProc = proc (): void {....gcsafe, thread.}
JobErrorHandler = proc (fut: Future[void]) {.closure, ...gcsafe.}
NextRunProc = proc (current: DateTime): Option[DateTime] {.closure, ...gcsafe,
    raises: [].}
Calculates the first scheduled instant strictly later than current. Return none(DateTime) when the schedule is empty or exhausted. Callbacks may capture mutable state; this type does not require deterministic results. Optional scheduling modules can use this callback without coupling their parser or data to the Metronome core.
Scheduler = ref object
Settings = ref object
  appName*: string
  errorHandler*: JobErrorHandler
Throttler = ref object
Throttle the total number of beats.

Vars

logger = newConsoleLogger(lvlAll, defaultFmtStr, false, defaultFlushThreshold)
By default, the logger is attached to no handlers. If you want to show logs, please call addHandler(logger).

Procs

proc `$`(beater: Beater): string {....raises: [], tags: [], forbids: [].}
proc failures(beater: Beater): int {....raises: [], tags: [], forbids: [].}
Return the number of job failures recorded for this beater.
proc failures(self: Scheduler; id: string): int {....raises: [], tags: [],
    forbids: [].}
Return the number of failures recorded for a registered job.
proc fire(self: Beater; errorHandler: JobErrorHandler = nil): owned(
    Future[void]) {....stackTrace: false,
                    raises: [Exception, ValueError, KeyError],
                    tags: [RootEffect, TimeEffect], forbids: [].}
Fire beats as async loop until no beats can be scheduled. Publish and wait for effective deadlines while advancing nominal cadence. Exhaustion clears nextRun but does not itself stop the beater. A one-shot stops after launch; running job futures may outlive this loop.
proc fireTime(self: Beater; prev: Option[DateTime]; now: DateTime): Option[
    DateTime] {....raises: [KeyError, Exception], tags: [RootEffect], forbids: [].}

Compute an effective launch candidate from explicit time inputs.

Reads the current schedule fields and delegates nominal calculation to internal helpers. prev is the previous nominal occurrence, independent of jitter and actual launch time. Interval jitter is sampled here on the beater; this call does not update runtime nextRun or launch a job. It shares deadline planning with fire, sampling once per eligible occurrence. A preview advances this beater's RNG; a later call or live execution samples independently and can return a different deadline. Pause/stop state and throttle capacity do not affect this preview. Zero or sub-millisecond jitter windows consume no random sample.

For bkInterval, it uses these rules:

  • Without prev, choose startTime when it is at or after now. Otherwise measure the interval at startTime in whole milliseconds and add the remaining cadence wait to now. An exact past cadence boundary advances a full interval; non-positive lengths return now.
  • With prev, add the calendar-relative interval to that nominal time, even when the result is behind now. Jitter and job duration do not become part of the nominal cadence.

Cron beaters delegate to cron matching, optionally in their configured timezone and returning in now's timezone; cron ignores prev and startTime. Custom beaters query their callback from now, or one nanosecond before a future startTime, independently of prev. One-shot beaters return their precise scheduled time, even if overdue, only while prev is none.

Built-in nominal calculations are deterministic for fixed inputs. A custom callback may carry mutable state, and interval jitter samples the RNG.

If self.endTime is set, both the nominal occurrence and the jittered deadline must be at or before it; otherwise none(DateTime) is returned.

proc id(beater: Beater): string {....raises: [], tags: [], forbids: [].}
Return the identifier assigned to this beater.
proc idle(self: Scheduler): owned(Future[void]) {....stackTrace: false,
    raises: [Exception, ValueError], tags: [RootEffect, TimeEffect], forbids: [].}
Idle the scheduler. It prevents the scheduler from shutdown when no beats is running.
proc initBeater(cron: Cron; asyncProc: BeaterAsyncProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil;
                timezone: Option[Timezone] = none(Timezone)): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}

Initialize a Beater, which kind is bkCron.

startTime, endTime, and timezone are optional. When timezone is set, cron matching is evaluated in that timezone and converted back to the caller's timezone for scheduling. Cron queries from the supplied current time; startTime is not a lower bound. endTime is an inclusive candidate bound, rather than a completion limit.

proc initBeater(cron: Cron; threadProc: BeaterThreadProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil;
                timezone: Option[Timezone] = none(Timezone)): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}

Initialize a Beater, which kind is bkCron.

startTime, endTime, and timezone are optional. When timezone is set, cron matching is evaluated in that timezone and converted back to the caller's timezone for scheduling. Cron queries from the supplied current time; startTime is not a lower bound. endTime is an inclusive candidate bound, rather than a completion limit.

proc initBeater(interval: TimeInterval; asyncProc: BeaterAsyncProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil;
                jitter: TimeInterval = initTimeInterval()): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}

Initialize a Beater, which kind is bkInterval.

startTime, endTime, and jitter are optional. Jitter adds a random non-negative delay to each interval launch without changing the base interval cadence. startTime defaults to construction time and anchors initial alignment; endTime is inclusive before and after jitter, rather than a completion limit.

proc initBeater(interval: TimeInterval; threadProc: BeaterThreadProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil;
                jitter: TimeInterval = initTimeInterval()): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}

Initialize a Beater, which kind is bkInterval.

startTime, endTime, and jitter are optional. Jitter adds a random non-negative delay to each interval launch without changing the base interval cadence. startTime defaults to construction time and anchors initial alignment; endTime is inclusive before and after jitter, rather than a completion limit.

proc initBeater(nextRunProc: NextRunProc; asyncProc: BeaterAsyncProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}

Initialize a custom-schedule Beater.

The callback must return the first instant strictly later than its input, or none(DateTime) when exhausted. A future startTime queries the callback at startTime minus one nanosecond, allowing that exact lower bound. endTime is inclusive. Callback results retain their precision and timezone. The callback runs during calculation on the calling thread and should return promptly. Live execution calls it on the event-loop thread.

proc initBeater(nextRunProc: NextRunProc; threadProc: BeaterThreadProc;
                startTime: Option[DateTime] = none(DateTime);
                endTime: Option[DateTime] = none(DateTime); id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}
Initialize a thread-backed custom-schedule Beater. The callback follows the same contract and bounds as the async overload.
proc initBeater(time: DateTime; asyncProc: BeaterAsyncProc; id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}
Initialize a one-shot Beater, which launches once at time.
proc initBeater(time: DateTime; threadProc: BeaterThreadProc; id: string = "";
                throttleNum: int = 1; errorHandler: JobErrorHandler = nil): Beater {.
    ...raises: [ValueError], tags: [TimeEffect], forbids: [].}
Initialize a one-shot Beater, which launches once at time.
proc initScheduler(settings: Settings): Scheduler {....raises: [], tags: [],
    forbids: [].}
Initialize a scheduler.
proc initThrottler(num: int = 1): Throttler {....raises: [ValueError], tags: [],
    forbids: [].}
Initialize the total number of beats allowed to be scheduled. By default, it's 1. If it's greater than 1, then more than one beats can be scheduled simultaneously.
proc jobState(self: Scheduler; id: string): Option[BeaterState] {....raises: [],
    tags: [], forbids: [].}
Return the lifecycle state for a registered job.
proc lastError(beater: Beater): ref Exception {....raises: [], tags: [],
    forbids: [].}
Return the most recent job error, or nil if no job has failed.
proc lastError(self: Scheduler; id: string): ref Exception {....raises: [],
    tags: [], forbids: [].}
Return the most recent error for a registered job, or nil.
proc lastErrorAt(beater: Beater): Option[DateTime] {....raises: [], tags: [],
    forbids: [].}
Return when this beater most recently recorded a job error.
proc lastErrorAt(self: Scheduler; id: string): Option[DateTime] {....raises: [],
    tags: [], forbids: [].}
Return when a registered job most recently recorded an error.
proc lastRun(beater: Beater): Option[DateTime] {....raises: [], tags: [],
    forbids: [].}
Return the wall-clock timestamp recorded after the last job invocation. This is an actual launch timestamp, independent of nominal cadence and completion; none(DateTime) means no job has been launched.
proc lastRun(self: Scheduler; id: string): Option[DateTime] {....raises: [],
    tags: [], forbids: [].}
Return the actual launch timestamp for a uniquely identified job, or none. This timestamp is recorded after invocation, independently of completion.
proc listJobs(self: Scheduler): seq[string] {....raises: [], tags: [], forbids: [].}
Return all non-empty registered job identifiers.
proc newSettings(appName = ""; errorHandler: JobErrorHandler = nil): Settings {.
    ...raises: [], tags: [], forbids: [].}
proc nextRun(beater: Beater): Option[DateTime] {....raises: [], tags: [],
    forbids: [].}
Return the pending effective launch deadline, including interval jitter. Reads execution state without calculating or sampling jitter. Returns none before a deadline is planned, while paused/stopped, or after exhaustion.
proc nextRun(self: Scheduler; id: string): Option[DateTime] {....raises: [],
    tags: [], forbids: [].}
Return the pending effective deadline for a uniquely identified job, or none. Reads execution state without calculating or sampling interval jitter. Before planning, while paused/stopped, and after exhaustion it is none.
proc pause(beater: Beater) {....raises: [], tags: [], forbids: [].}
Pause future launches and clear the pending deadline without cancelling jobs.
proc pause(self: Scheduler; id: string): bool {....raises: [], tags: [],
    forbids: [].}
Pause a registered job by identifier.
proc register(self: Scheduler; beater: Beater) {....raises: [], tags: [],
    forbids: [].}
Register a beater.
proc resume(beater: Beater) {....raises: [], tags: [TimeEffect], forbids: [].}
Resume launches; intervals advance from resume time and pending one-shots remain.
proc resume(self: Scheduler; id: string): bool {....raises: [], tags: [TimeEffect],
    forbids: [].}
Resume a registered job by identifier.
proc runningCount(beater: Beater): int {....raises: [], tags: [], forbids: [].}
Return the number of currently running jobs for this beater.
proc runningCount(self: Scheduler; id: string): int {....raises: [], tags: [],
    forbids: [].}
Return the number of currently running jobs for a registered job.
proc serve(self: Scheduler) {....raises: [Exception, ValueError, KeyError, OSError],
                              tags: [RootEffect, TimeEffect], forbids: [].}
Serve the scheduler. It's a blocking function.
proc start(self: Scheduler): owned(Future[void]) {....stackTrace: false,
    raises: [Exception, ValueError, KeyError], tags: [RootEffect, TimeEffect],
    forbids: [].}
Start and retain fire loops, returning without waiting for jobs to finish. Each call starts new loops; there is no restart guard.
proc state(beater: Beater): BeaterState {....raises: [], tags: [], forbids: [].}
Return the current lifecycle state for this beater.
proc stop(beater: Beater) {....raises: [], tags: [], forbids: [].}
Stop future launches permanently, allowing running jobs to finish.
proc stop(self: Scheduler; id: string): bool {....raises: [], tags: [], forbids: [].}
Stop a registered job by identifier.
proc stopAll(self: Scheduler) {....raises: [], tags: [], forbids: [].}
Stop future launches for all registered jobs, allowing active jobs to finish.
proc submit(self: Throttler; fut: Future[void]) {....raises: [], tags: [],
    forbids: [].}
Submit a new future to the throttler. WARNING: this function does not perform throttling check.
proc throttled(self: Throttler): bool {....raises: [], tags: [], forbids: [].}
Whether the throttler is allowed to schedule more beats.
proc waitFor(self: Scheduler) {....raises: [ValueError, Exception, OSError,
    KeyError], tags: [TimeEffect, RootEffect], forbids: [].}
Block until scheduler startup returns, without waiting for jobs to finish.

Macros

macro metronome(body: untyped): untyped

Initialize a scheduler, register code blocks as beats, and run it as a blocking application.

You'll use it when the scheduled jobs are the only thing your programm will need to handle.

macro scheduler(sched: untyped; body: untyped)

Initialize a scheduler and register code blocks as beats.

Use it when running Metronome alongside another event-driven library, such as a web framework.