Schedules: start workflows at due times
A schedule starts a registered workflow at each of its due times. Ada wants a reminder every day at
09:00, Oslo time. The reminder is a workflow whose input is a ScheduledRun, and a schedule starts
it:
Shared setup
module Account =
open FCQRS.Common
// What a caller, or a transfer, can ask an account to do.
type AccountCommand =
| Open of owner: string
| Deposit of amount: decimal
| Withdraw of amount: decimal
| SendTransfer of transferId: string * target: string * amount: decimal
| ReceiveTransfer of transferId: string * source: string * amount: decimal
| RefundTransfer of transferId: string * target: string * amount: decimal
// What the account replies. Rejected is a reply only: it is never stored.
type AccountEvent =
| Opened of owner: string
| Deposited of amount: decimal
| Withdrawn of amount: decimal
| TransferSent of transferId: string * target: string * amount: decimal
| TransferReceived of transferId: string * source: string * amount: decimal
| TransferRefunded of transferId: string * target: string * amount: decimal
| Rejected of reason: string
// What the account knows now. The sets hold the IDs of transfers it has
// handled, so a repeated transfer command moves no money twice.
type AccountState = {
Owner: string option
Balance: decimal
Sent: Set<string>
Received: Set<string>
Refunded: Set<string>
}
// The state before the account's first event.
let initial = {
Owner = None
Balance = 0m
Sent = Set.empty
Received = Set.empty
Refunded = Set.empty
}
// Chooses what to do with a command, based on the current state.
let decide (command: Command<AccountCommand>) (state: AccountState) =
match command.CommandDetails, state.Owner with
| Open _, Some _ -> DeferEvent(Rejected "The account is already open")
| Open owner, None -> PersistEvent(Opened owner)
| _, None -> DeferEvent(Rejected "The account is not open")
// A repeated send gets the first answer, checked before the balance,
// because the first send lowered it. No money moves twice.
| SendTransfer(id, target, amount), _ when state.Sent.Contains id ->
DeferEvent(TransferSent(id, target, amount))
| (Deposit amount | Withdraw amount | SendTransfer(_, _, amount)), _
when amount <= 0m -> DeferEvent(Rejected "The amount must be positive")
| Deposit amount, _ -> PersistEvent(Deposited amount)
| (Withdraw amount | SendTransfer(_, _, amount)), _
when amount > state.Balance ->
DeferEvent(Rejected $"Insufficient funds: {state.Balance} available")
| Withdraw amount, _ -> PersistEvent(Withdrawn amount)
| SendTransfer(id, target, amount), _ ->
PersistEvent(TransferSent(id, target, amount))
// A repeated delivery gets the first answer; no money moves.
| ReceiveTransfer(id, source, amount), _ when state.Received.Contains id ->
DeferEvent(TransferReceived(id, source, amount))
| ReceiveTransfer(id, source, amount), _ ->
PersistEvent(TransferReceived(id, source, amount))
| RefundTransfer(id, target, amount), _ when state.Refunded.Contains id ->
DeferEvent(TransferRefunded(id, target, amount))
| RefundTransfer(id, target, amount), _ ->
PersistEvent(TransferRefunded(id, target, amount))
// Applies one event. A rejection or a repeated reply changes nothing.
let fold (event: Event<AccountEvent>) (state: AccountState) =
match event.EventDetails with
| Opened owner -> { state with Owner = Some owner }
| Deposited amount -> { state with Balance = state.Balance + amount }
| Withdrawn amount -> { state with Balance = state.Balance - amount }
| TransferSent(id, _, _) when state.Sent.Contains id -> state
| TransferSent(id, _, amount) ->
{ state with
Balance = state.Balance - amount
Sent = state.Sent.Add id
}
// FCQRS folds a repeated reply too; a known ID changes nothing.
| TransferReceived(id, _, _) when state.Received.Contains id -> state
| TransferReceived(id, _, amount) ->
{ state with
Balance = state.Balance + amount
Received = state.Received.Add id
}
| TransferRefunded(id, _, _) when state.Refunded.Contains id -> state
| TransferRefunded(id, _, amount) ->
{ state with
Balance = state.Balance + amount
Refunded = state.Refunded.Add id
}
| Rejected _ -> state
open System
open System.Threading.Tasks
open FCQRS.Common
open FCQRS.FSharp
open FCQRS.Workflows
open Account
let score (key: string) (order: string) : Task<int> = Task.FromResult 42
let charge (key: string) (amount: decimal) : Task<string> = Task.FromResult "paid"
let isShipped (key: string) (order: string) : Task<bool> = Task.FromResult true
let sendReminder (key: string) (text: string) : Task<string> = Task.FromResult "sent"
type ReservationCommand = Reserve of id: string
type ReservationEvent =
| Reserved of id: string
| Confirmed of id: string
Fcqrs_450-concepts_013-schedules.md_page.AccountFCQRSFCQRS.CommonContains common types like Events and Commands Functionality for Write Side.
Fcqrs_450-concepts_013-schedules.md_page.Account.AccountCommandOpenowner: stringstringAn abbreviation for the CLI type . Basic Types
Depositamount: decimaldecimalAn abbreviation for the CLI type . Basic Types
WithdrawSendTransfertransferId: stringtarget: stringReceiveTransfersource: stringRefundTransferFcqrs_450-concepts_013-schedules.md_page.Account.AccountEventOpenedDepositedWithdrawnTransferSentTransferReceivedTransferRefundedRejectedreason: stringFcqrs_450-concepts_013-schedules.md_page.Account.AccountStateOwner: string optionoptionThe type of optional values. When used from other CLI languages the empty option is the null value. Use the constructors Some and None to create values of this type. Use the values in the Option module to manipulate values of this type, or pattern match against the values directly. 'None' values will appear as the value null to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of null as a value representation. Options
Balance: decimalSent: Set<string>Microsoft.FSharp.Collections.FSharpSet`1Immutable sets based on binary trees, where elements are ordered by F# generic comparison. By default comparison is the F# structural comparison function or uses implementations of the IComparable interface on element values. See the module for further operations on sets. All members of this class are thread-safe and may be used concurrently from multiple threads.
Received: Set<string>Refunded: Set<string>initial: AccountStateNoneThe representation of "No value"
Microsoft.FSharp.Collections.SetModuleContains operations for working with values of type .
empty: Set<'T>The empty set for the type 'T. Set.empty<int> Evaluates to set [ ]. This is an O(1) operation.
decide: Command<AccountCommand> -> AccountState -> EventAction<AccountEvent>command: Command<AccountCommand>FCQRS.Common.Command`1Represents a command to be processed by an aggregate actor. <typeparam name="'CommandDetails">The specific type of the command payload.</typeparam>
state: AccountStateCommandDetails: 'CommandDetailsThe specific details or payload of the command.
SomeThe representation of "Value of type 'T" The input value. An option representing the value.
DeferEventPublish and fold the event in the live actor without storing it or incrementing the persisted version. A deferred event does not start a saga; running sagas still receive it.
PersistEventPersist the event to the journal. The actor's state will be updated using the event handler *after* persistence succeeds.
id: stringContains: string -> boolA useful shortcut for Set.contains. See the Set module for further operations on sets. The value to check. True if the set contains value. let set = Set.empty.Add(2).Add(3) printfn $"Does the set contain 1? {set.Contains(1)}" The sample evaluates to the following output: Does the set contain 1? false This is an O(log n) operation, where n is the number of elements in the set.
(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
(>): 'T -> 'T -> boolStructural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false
fold: Event<AccountEvent> -> AccountState -> AccountStateevent: Event<AccountEvent>FCQRS.Common.Event`1Represents an event generated by an aggregate actor as a result of processing a command. <typeparam name="'EventDetails">The specific type of the event payload.</typeparam>
EventDetails: 'EventDetailsThe specific details or payload of the event.
(-): ^T1 -> ^T2 -> ^T3Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8
Add: string -> Set<string>A useful shortcut for Set.add. Note this operation produces a new set and does not mutate the original set. The new set will share many storage nodes with the original. See the Set module for further operations on sets. The value to add to the set. The result set. let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The new set is: {set}" The sample evaluates to the following output: The new set is: set [1; 2] This is an O(log n) operation, where n is the number of elements in the set.
(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World"
SystemThreadingTasksFCQRS.FSharpIdiomatic-F# functional facade for FCQRS. Gives F# consumers the same one-call ergonomics the C# host-builder (HostExtensions.fs) gives C#, but with F# idioms: records-of-functions for the definitions, typed handles for the results, an explicit wiring pipeline, and plain helpers for saga side effects. It is a *pure addition* that wraps only the existing primitives (IActor.InitializeActor / SagaBuilder.initSimple / Projections.startTracked / InitializeSagaStarter / CreateCommandSubscription / Actor.api) and changes nothing in the C# interop layer or the core. open FCQRS.FSharp let api = Fcqrs.actor config loggerFactory (Some (Fcqrs.connect DBType.Sqlite conn)) "Cluster" let documents = Fcqrs.aggregate api { Name="Document"; Initial=...; Decide=...; Fold=... } let slugs = Fcqrs.aggregate api { Name="Slug"; Initial=...; Decide=...; Fold=... } let publication = Fcqrs.saga api (publicationDef documents.Factory slugs.Factory) Fcqrs.wireSagaStarters api [ publication ] let subs = Fcqrs.projection api (Projection.single 0 updateReadModel) // (Projection.multi when you must control which notifications publish) // send a command and await the matching aggregate reply: let! ev = documents.Send (Fcqrs.newCid()) (Fcqrs.aggregateId id) cmd (fun e -> ...)
Workflowsscore: string -> string -> Task<int>key: stringorder: stringSystem.Threading.Tasks.Task`1Represents an asynchronous operation that can return a value. The type of the result produced by this .
intAn abbreviation for the CLI type . Basic Types
System.Threading.Tasks.TaskRepresents an asynchronous operation.
FromResult: 'TResult -> Task<'TResult>Creates a that's completed successfully with the specified result. The result to store into the completed task. The type of the result returned by the task. The successfully completed task.
charge: string -> decimal -> Task<string>isShipped: string -> string -> Task<bool>boolAn abbreviation for the CLI type . Basic Types
sendReminder: string -> string -> Task<string>text: stringFcqrs_450-concepts_013-schedules.md_page.ReservationCommandReserveFcqrs_450-concepts_013-schedules.md_page.ReservationEventReservedConfirmedlet remind =
Workflow.define "remind" (fun (run: ScheduledRun<string>) -> workflow {
let retry = Retry.times 3 (TimeSpan.FromSeconds 30.0)
return!
activity "send" retry (fun attempt ->
sendReminder attempt.IdempotencyKey run.Input)
})
let startReminders (api: IActor) =
async {
let reminders = Workflows.register api remind
let schedules =
Schedules.register api [ ScheduledWorkflow.ofHandle reminders ]
// Schedule commands raise until the starters are wired.
Fcqrs.wireSagaStarters api []
do!
Schedules.createLatest schedules "ada-daily" "remind" "Drink water"
(ScheduleRule.Daily(TimeOnly(9, 0), "Europe/Oslo"))
return schedules
}
remind: WorkflowDefinition<ScheduledRun<string>,string>FCQRS.Workflows.WorkflowDefines workflows.
define: string -> ('Input -> Workflow<'Result>) -> WorkflowDefinition<'Input,'Result>A workflow named `name` whose instances run `body` on their input.
run: ScheduledRun<string>FCQRS.Workflows.ScheduledRun`1The input of a run that a schedule starts. A workflow body cannot read its own ID, so the run gets the ID of its schedule and the due time it serves.
stringAn abbreviation for the CLI type . Basic Types
workflow: WorkflowBuilderBuilds a workflow: `workflow { let! x = activity ... }`.
retry: RetryPolicyFCQRS.Workflows.RetryCommon retry policies.
times: int -> TimeSpan -> RetryPolicyAt most `attempts` attempts, with backoff from one second to one minute. Each attempt fails when it has not finished within `attemptTimeout`.
System.TimeSpanRepresents a time interval.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
activity: string -> RetryPolicy -> (AttemptContext -> Task<'T>) -> Workflow<'T>Calls an external system. The call runs at least once: a crash after the call and before its result is stored repeats it, so pass `IdempotencyKey` to the external system. `name` is stored and must not change while instances are running. The policy needs an `AttemptTimeout` or a `Deadline`: an attempt with neither would wait as long as its call, also for a call that ignores its cancellation token.
attempt: AttemptContextsendReminder: string -> string -> Task<string>IdempotencyKey: stringThe same for every attempt of this step, across restarts: workflow name, workflow ID, and step path. Pass it to the external system so a repeated call is recognised.
Input: 'InputThe schedule's input.
startReminders: IActor -> Async<ScheduleHandle>api: IActorFCQRS.Common.IActorDefines the core functionalities and context provided by the FCQRS environment to actors. This interface provides access to essential Akka.NET services and FCQRS initialization methods.
async: AsyncBuilderBuilds an asynchronous workflow using computation expression syntax. let sleepExample() = async { printfn "sleeping" do! Async.Sleep 10 printfn "waking up" return 6 } sleepExample() |> Async.RunSynchronously
reminders: WorkflowHandle<ScheduledRun<string>,string>FCQRS.Workflows.WorkflowsRegisters workflows with an actor system.
register: IActor -> WorkflowDefinition<'Input,'Result> -> WorkflowHandle<'Input,'Result>Registers the workflow and returns its handle. Instances that were running when the process last stopped resume as soon as this is called.
schedules: ScheduleHandleFCQRS.Workflows.SchedulesSchedules that start a registered workflow at each due time. A schedule is created, changed, paused, resumed and deleted while the application runs, and is stored in the journal as an aggregate named "fcqrs-schedule". The run for a due time is a workflow instance whose ID is the schedule's ID, "@", and the due time in UTC in ISO 8601 ("O") form. A run starts at least once per accepted due time, and a repeated start with its ID stores nothing.
register: IActor -> ScheduledWorkflow list -> ScheduleHandleRegisters the schedule aggregate and starts this actor system's dispatcher, which may start the listed workflows. Register each workflow with `Workflows.register` first. Raises `InvalidOperationException` when the actor system has a dispatcher already, and `Akka.Configuration.ConfigurationException` when `akka.fcqrs.schedule-check-interval` is not positive. A schedule whose workflow is not listed starts no run, and the dispatcher logs an error at each of its due times, until a later start lists the workflow again. The schedule aggregate, like every aggregate, waits for the actor system's saga starters before it stores an event, and terminates the process when they are not wired within `akka.fcqrs.saga-start-timeout`. Wire them with `Fcqrs.wireSagaStarters` after registering every aggregate and saga, this one included. Until they are wired the dispatcher fires nothing, and every function of this module that sends a command raises `InvalidOperationException`. The dispatcher keeps its index in the table `fcqrs_schedule_index`, which it creates on first use in the journal's database and schema, with one row per schedule. A start reads the rows and the schedule events stored since, so it does not read the schedules' whole history again. The first start on a journal without the table reads that history once and fills the table. Raises `ArgumentException` when Akka's query journal and write journal differ in connection string, schema, table, or columns, because the table must live in the journal it reads.
FCQRS.Workflows.ScheduledWorkflowModuleMakes a `ScheduledWorkflow`.
ofHandle: WorkflowHandle<ScheduledRun<'Input>,'Result> -> ScheduledWorkflowA workflow registered with `Workflows.register` whose input is a `ScheduledRun`.
FCQRS.FSharp.FcqrswireSagaStarters: IActor -> SagaHandle list -> unitWire every registered saga into one saga-starter (or the empty starter if none). Call after the aggregates + sagas are registered.
createLatest: ScheduleHandle -> string -> string -> 'Input -> ScheduleRule -> Async<unit>`create` with `CatchUp.Latest`, the default policy: after downtime, the schedule starts one run, for the most recent missed due time. Raises as `create` does. C#'s `CreateAsync` without a policy calls it.
FCQRS.Workflows.ScheduleRuleWhen a schedule is due, written `ScheduleRule.Daily`, `ScheduleRule.Weekly`, `ScheduleRule.Every`, `ScheduleRule.DailyAt`, `ScheduleRule.WeeklyAt` or `ScheduleRule.Monthly`. A rule is stored in the schedule's journal, so its cases and fields are a persistent contract.
DailyEvery day at a local time in a time zone. The zone is a time-zone ID such as "Europe/Oslo".
``.ctor``: int * int -> unitInitializes a new instance of the structure to the specified hour and the minute. The hours (0 through 23). The minutes (0 through 59).
public sealed class Remind()
: Workflow<ScheduledRun<string>, string>("remind")
{
public override async WorkflowTask<string> Run(
WorkflowContext ctx, ScheduledRun<string> run) =>
await ctx.Activity(
"send", Retry.times(3, TimeSpan.FromSeconds(30)),
attempt => SendReminder(attempt.IdempotencyKey, run.Input));
}
public static class Reminders
{
public static async Task<ScheduleClient> Start(IActor actor)
{
var reminders = WorkflowHost.Register(actor, new Remind());
var schedules = ScheduleHost.Register(
actor, ScheduleHost.Workflow(reminders));
// Schedule commands throw until the starters are wired.
ActorWiring.InitSagaStarterEmpty(actor);
await schedules.CreateAsync("ada-daily", "remind", "Drink water",
ScheduleRule.NewDaily(new TimeOnly(9, 0), "Europe/Oslo"));
return schedules;
}
}
Schedules.register registers the schedule aggregate, fcqrs-schedule, and starts the actor
system's one dispatcher, which starts runs of the listed workflows only. The list takes each
workflow's handle, so the workflows are registered first. Like every aggregate, a schedule stores no
event until the saga starters are wired, so call Fcqrs.wireSagaStarters once, after every aggregate
and saga is registered, as the aggregate guide describes.
Schedules.createLatest creates the schedule with the default catch-up policy, CatchUp.Latest.
Schedules.create takes the policy as its last argument. In C#, CreateAsync without a policy uses
CatchUp.Latest, and an overload takes one. A create returns once the schedule is stored, and a
second create with the same content stores nothing, so a program can create its schedules at every
start.
A C# host built with AddFcqrs wires the saga starters when the host starts, so register the
schedules from a singleton resolved after the host has started:
builder.Services.AddFcqrs(connectionString, "reminders");
builder.Services.AddWorkflow<Remind, ScheduledRun<string>, string>();
builder.Services.AddSingleton(services => ScheduleHost.Register(
services.GetRequiredService<IActor>(),
ScheduleHost.Workflow(services.GetRequiredService<
IWorkflowClient<ScheduledRun<string>, string>>())));
using var host = builder.Build();
await host.StartAsync();
var schedules = host.Services.GetRequiredService<ScheduleClient>();
await schedules.CreateAsync("ada-daily", "remind", "Drink water",
ScheduleRule.NewDaily(new TimeOnly(9, 0), "Europe/Oslo"));
A run starts at least once per due time
The schedule aggregate decides each run, and the dispatcher starts it:
- The dispatcher asks the schedule to fire for a due time. The schedule decides from its own state whether that due time runs, and stores the workflow and the input the run gets. The dispatcher's index of schedules is only a hint: an index that has not seen a pause, change, or delete cannot start a run for a paused or deleted schedule, or for a due time that a change removed.
- The dispatcher starts the run. Its workflow ID is
<schedule>@<due UTC>: the schedule's ID,@, and the due time in UTC in ISO 8601 form, such asada-daily@2026-11-15T08:00:00.0000000Z. Its input isScheduledRun { Schedule; Due; Input }, because a workflow body cannot read its own ID. - The dispatcher reports the start, and the schedule stores it.
A pause stored before step 1 stops the run. A crash after step 1 leaves a decided run with no reported start. After the restart the dispatcher starts it again with the same ID, and a second start of an existing workflow stores nothing. A run therefore starts at least once for each due time the schedule accepts, and one workflow instance serves it. A run is an ordinary workflow instance: one that faults ends only that instance, and one still going at the next due time runs alongside the next run.
Due times, downtime, and changes
ScheduleRule.Daily(time, zone) and ScheduleRule.Weekly(days, time, zone) take a local time and a
time-zone ID. Due times are computed in the zone and stored in UTC, so Ada's reminder runs at 09:00
Oslo time in winter (08:00 UTC) and in summer (07:00 UTC). A local time that a clock change skips
runs at the next local time that exists, and one that occurs twice runs once, at the first
occurrence. ScheduleRule.Every interval counts from the creation or the last change.
Ada also pays rent on the last day of each month and wants a reminder in the morning and in the evening of that day:
let remindRent (schedules: ScheduleHandle) =
// 09:00 and 18:00, Oslo time, on the last day of each month.
let rule =
ScheduleRule.Monthly(
[ MonthDay.LastDay ],
[ TimeOnly(9, 0); TimeOnly(18, 0) ],
"Europe/Oslo"
)
Schedules.createLatest schedules "ada-rent" "remind" "Pay the rent" rule
remindRent: ScheduleHandle -> Async<unit>schedules: ScheduleHandleFCQRS.Workflows.ScheduleHandleThe registered schedule dispatcher. Pass it to the functions of `Schedules`.
rule: ScheduleRuleFCQRS.Workflows.ScheduleRuleWhen a schedule is due, written `ScheduleRule.Daily`, `ScheduleRule.Weekly`, `ScheduleRule.Every`, `ScheduleRule.DailyAt`, `ScheduleRule.WeeklyAt` or `ScheduleRule.Monthly`. A rule is stored in the schedule's journal, so its cases and fields are a persistent contract.
MonthlyOn the listed days of each month at each of the listed local times in a time zone. The days and times form one set of local date-times per month: a date-time that two entries name, such as `Day 31` and `LastDay` in a 31-day month, is due once.
FCQRS.Workflows.MonthDayA day of the month for `ScheduleRule.Monthly`, written `MonthDay.Day 15`, `MonthDay.LastDay`, `MonthDay.Nth(3, DayOfWeek.Wednesday)` or `MonthDay.Last DayOfWeek.Thursday`. Stored in the schedule's journal, so its cases and fields are a persistent contract.
LastDayThe month's last day.
``.ctor``: int * int -> unitInitializes a new instance of the structure to the specified hour and the minute. The hours (0 through 23). The minutes (0 through 59).
FCQRS.Workflows.SchedulesSchedules that start a registered workflow at each due time. A schedule is created, changed, paused, resumed and deleted while the application runs, and is stored in the journal as an aggregate named "fcqrs-schedule". The run for a due time is a workflow instance whose ID is the schedule's ID, "@", and the due time in UTC in ISO 8601 ("O") form. A run starts at least once per accepted due time, and a repeated start with its ID stores nothing.
createLatest: ScheduleHandle -> string -> string -> 'Input -> ScheduleRule -> Async<unit>`create` with `CatchUp.Latest`, the default policy: after downtime, the schedule starts one run, for the most recent missed due time. Raises as `create` does. C#'s `CreateAsync` without a policy calls it.
public static Task RemindRent(ScheduleClient schedules)
{
// 09:00 and 18:00, Oslo time, on the last day of each month.
var rule = ScheduleRule.NewMonthly(
[MonthDay.LastDay],
[new TimeOnly(9, 0), new TimeOnly(18, 0)],
"Europe/Oslo");
return schedules.CreateAsync("ada-rent", "remind", "Pay the rent", rule);
}
A monthly rule's days can also be a day number, such as MonthDay.Day 15, or a weekday such as
MonthDay.Nth(3, DayOfWeek.Wednesday) or MonthDay.Last DayOfWeek.Thursday. Day 31 runs on the
last day of a shorter month. ScheduleRule.DailyAt and ScheduleRule.WeeklyAt take several times a
day. The Schedules reference lists every rule.
A due time is missed when the dispatcher could not fire on time, for example while the process was stopped. The catch-up policy decides which missed due times run:
| Case | What runs |
|---|---|
Missed due times, CatchUp.Latest (the default) |
One run, for the most recent |
Missed due times, CatchUp.All |
One run for each, oldest first, at most for the 1000 most recent |
Missed due times, CatchUp.None |
None; the schedule waits for the next due time. A fire up to one minute late still counts as on time |
Schedules.pause, then Schedules.resume |
Nothing during the pause. Runs continue from the first due time after the resume: a due time inside the pause never runs, whatever the policy |
Schedules.change |
The new workflow, input, rule, and policy. No due time at or before the change runs |
Schedules.delete |
Nothing more. The ID cannot be used for a new schedule, so a run ID never belongs to two schedules |
| A run decided before a change, pause, or delete | The run still starts, on the workflow and with the input stored when it was decided |
A fire more than one second before its due time is refused, so a fault in the dispatcher cannot start a run more than a second early.
What a schedule does not guarantee
- Exactly-once side effects. A run's steps follow the workflow rules: an activity runs at least once. Its idempotency key includes the run's ID, so it differs per due time and stays the same across the attempts of one run. The external system must honour it.
- Precision below a second. A run starts after its due time, once the dispatcher has woken, the schedule has stored its decision, and the run's start is stored.
- More than one node. The dispatcher assumes it is the only one, and FCQRS runs on one node.
- A run whose stored input no longer reads. After a deploy that changes a workflow's input type, a decided run whose stored input the workflow cannot read is lost, and one logged error is the only signal.
The application chooses each user's time zone, keeps run steps safe to repeat, and treats the workflow's name and the input's stored form as persistent contracts: every schedule stores both.
C# equivalents
| F# | C# |
|---|---|
Schedules.register api [ ScheduledWorkflow.ofHandle handle ] |
ScheduleHost.Register(actor, ScheduleHost.Workflow(client)) |
Schedules.createLatest, with the default CatchUp.Latest |
schedules.CreateAsync(id, workflow, input, rule) |
Schedules.create, Schedules.change |
schedules.CreateAsync, schedules.ChangeAsync, with a CatchUp |
Schedules.pause, resume, delete |
schedules.PauseAsync, ResumeAsync, DeleteAsync |
Schedules.state, None when the index has not read it |
schedules.State(id), null when the index has not read it |
ScheduleRule.Daily(time, zone) |
ScheduleRule.NewDaily(time, zone), and NewWeekly, NewEvery, NewDailyAt, NewWeeklyAt, NewMonthly |
MonthDay.Nth(3, DayOfWeek.Wednesday), MonthDay.LastDay |
MonthDay.NewNth(3, DayOfWeek.Wednesday), MonthDay.LastDay, and NewDay, NewLast |
Schedules reference lists the exceptions each call raises, the ID limits, the dispatcher's timing, the index table and the database rights it needs, what a deploy can break, and every persistent contract. Run scheduled jobs builds a nightly backup and a weekly invoice as runnable F# and C# programs.
Next: Free programs describes logic as instructions that an interpreter, such as a workflow, carries out.