jobPlannamespacenamespace jobPlanThe operating system's own scheduled job, planned without touching it (commons 0001-system FR-017): from a job's name, the argument vector it runs, its working folder, its environment and when it runs, planJob gives the files to write and the commands that load and unload the job, for one of three schedulers, and writes or runs nothing itself (runtime/schedule.ts does).
| OS | what is planned | loaded by |
|---|---|---|
| Linux | a systemd user service (one shot) and its timer in ~/.config/systemd/user/ | systemctl --user enable --now <label>.timer |
| macOS | a LaunchAgent, ~/Library/LaunchAgents/<label>.plist | launchctl bootstrap gui/<uid> <plist> |
| Windows | a .cmd file in ~\AppData\Local\<folder>\ and a Task Scheduler task | schtasks /Create /F /TN <folder>\<name> /TR ... |
The caller names its jobs with an owner: a reverse-DNS domain (org.example.backup), which makes the launchd label and the systemd unit <domain>.<name>, and a Task Scheduler folder (Example), which makes the task <folder>\<name> and the folder of its .cmd file. Paths in files are relative to the user's home folder, with / between their parts, so the caller writes them on any host; the absolute paths the commands need (the plist for launchctl, the .cmd file for schtasks) are built from the given home folder with the target's own separator.
When a job runs is one of five kinds, each expressed on every scheduler at the same minutes of local time:
| kind | systemd OnCalendar= | launchd StartCalendarInterval | schtasks |
|---|---|---|---|
minutes | *-*-* *:00/N:00 | one Minute dict for each of 0, N, 2N.. | /SC MINUTE /MO N /ST 00:00 |
hourly | *-*-* *:MM:00 | Minute | /SC HOURLY /ST 00:MM |
daily | *-*-* HH:MM:00 | Hour, Minute | /SC DAILY /ST HH:MM |
weekly | Fri *-*-* HH:MM:00 | Weekday (0 is Sunday), Hour, Minute | /SC WEEKLY /D FRI /ST HH:MM |
monthly | *-*-DD HH:MM:00 | Day, Hour, Minute | /SC MONTHLY /D DD /ST HH:MM |
minutes takes a divisor of 60 below 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30), so that all three run at the same minutes of every hour; monthly takes a day from 1 to 28, which every month has.
Every argument is quoted for the file that carries it, and what cannot be carried safely is refused with a ScheduleError, never altered. systemd's ExecStart= and Environment= get double quotes with C escapes (\\, \", \t, \xHH), %% for % and, in ExecStart=, $$ for $; a carriage return, a line feed or NUL is refused, and so is an argument that is only ; and a program that begins with one of systemd's prefixes (@-:+!|). The .cmd file gets double quotes around any argument that is not plain, %% for % (a batch file's own escape, inside quotes or not), the trailing backslashes of a quoted argument doubled (the C runtime's rule), delayed expansion turned off (so ! is plain) and the UTF-8 code page; a double quote (cmd.exe's quoting cannot hold one safely) and any control character but tab are refused. The plist is written with the kernel's XML writer, which escapes the markup; a character XML cannot carry (a control character but tab and line feed, a carriage return, which XML reads as a line feed, or a lone surrogate) is refused.
Taken from Stolos's src/archon/export/schedule.ts (spec 092), which built the jobs of stolos export schedule from an export job and a fleet. What changed: the job is generic (an argument vector, a working folder, an environment, an optional log) and named by the caller's owner instead of Stolos's; the schedule is a discriminated union, with every N minutes added; the files are relative to the home folder; the plist is built as an XML tree; quoting follows each format's rules in full and refuses what it cannot hold, where Stolos quoted a few characters; and errors are values.
import { jobName, planJob, schedule } from "./job-plan.ts";
const name = jobName("backup");
const when = schedule({ kind: "daily", hour: 6, minute: 10 });
if (name.kind === "ok" && when.kind === "ok") {
const plan = planJob(
{ name: name.value, owner: { domain: "org.example", folder: "Example" }, argv: ["/usr/bin/backup", "--all"], workdir: "/srv", when: when.value },
{ os: "linux", home: "/home/ada" },
);
// plan.value.files: .config/systemd/user/org.example.backup.service and .timer, with OnCalendar=*-*-* 06:10:00
// plan.value.install: systemctl --user daemon-reload, then systemctl --user enable --now org.example.backup.timer
}jobPlannamespacenamespace jobPlanjobPlan.SchedulerOstypeno test imports ittype SchedulerOs = "linux" | "darwin" | "windows";The schedulers a job can be planned for: systemd on Linux, launchd on macOS, Task Scheduler on Windows.
jobPlan.ScheduleErrortypeno test imports ittype ScheduleError = {
readonly kind: "schedule";
readonly field: string;
readonly reason: "invalid" | "unsafe";
readonly message: string;
};Why a job cannot be planned: the field at fault (name, argv[2], env.PATH, when.minute...), and whether its value is not valid or cannot be carried safely.
jobPlan.formatScheduleErrorfunctionno test imports itfunction formatScheduleError(e: ScheduleError): stringA schedule error as one line: argv[1]: a line feed cannot be carried in a systemd unit.
jobPlan.JobNametypeno test imports ittype JobName = Brand<string, "JobName">;A job's name, safe in a file name, a unit name, a plist label and a task name: 1 to 64 lowercase letters, digits and dashes, beginning and ending with a letter or digit.
jobPlan.jobNamefunctionno test imports itfunction jobName(s: string): Result<JobName, ScheduleError>A job's name, validated.
jobPlan.Weekdaytypeno test imports ittype Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";The day of a weekly schedule.
jobPlan.Whentypeno test imports ittype When =
| { readonly kind: "minutes"; readonly every: number }
| { readonly kind: "hourly"; readonly minute: num… (411 characters)type When =
| { readonly kind: "minutes"; readonly every: number }
| { readonly kind: "hourly"; readonly minute: number }
| { readonly kind: "daily"; readonly hour: number; readonly minute: number }
| { readonly kind: "weekly"; readonly day: Weekday; readonly hour: number; readonly minute: number }
| { readonly kind: "monthly"; readonly day: number; readonly hour: number; readonly minute: number };When a job runs, in local time: every N minutes on the clock, every hour at a minute, every day, every week on a day, or every month on a day.
jobPlan.Scheduletypeno test imports ittype Schedule = Brand<When, "Schedule">;A When whose numbers are in range, made only by schedule.
jobPlan.MINUTE_STEPSconstno test imports itconst MINUTE_STEPS: readonly number[]The intervals minutes takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour.
jobPlan.schedulefunctionno test imports itfunction schedule(when: When): Result<Schedule, ScheduleError>A schedule, validated: hours 0 to 23, minutes 0 to 59, a day of the month 1 to 28, a weekday by its three letters, a step of MINUTE_STEPS.
jobPlan.describeSchedulefunctionno test imports itfunction describeSchedule(s: Schedule): stringWhen a schedule runs, as a sentence's end: every 15 minutes, every hour at minute 05, every day at 06:10, every Friday at 08:00, on day 3 of every month at 05:00.
jobPlan.onCalendarfunctionno test imports itfunction onCalendar(s: Schedule): stringsystemd's OnCalendar= expression for a schedule (systemd.time(7)).
jobPlan.CalendarIntervaltypeno test imports ittype CalendarInterval = { readonly Minute: number; readonly Hour?: number; readonly Day?: number; readonly Weekday?: number };One launchd calendar interval: the job runs whenever every key given matches (Weekday 0 is Sunday).
jobPlan.calendarIntervalsfunctionno test imports itfunction calendarIntervals(s: Schedule): readonly CalendarInterval[]launchd's StartCalendarInterval for a schedule: one interval, or one for each minute of the hour the job runs at.
jobPlan.schtasksSchedulefunctionno test imports itfunction schtasksSchedule(s: Schedule): readonly string[]The arguments schtasks /Create takes for a schedule, from /SC on.
jobPlan.quoteSystemdArgfunctionno test imports itfunction quoteSystemdArg(arg: string, first?: boolean): Result<string, ScheduleError>One argument as a word of systemd's ExecStart= (systemd.service(5), "Command lines"): as it is where it is plain, else in double quotes with C escapes, %% for a specifier's % and $$ for a variable's $. Refused: NUL, a carriage return or a line feed; an argument that is only ; (a command separator); and, for the program (first), an empty one or one that begins with a prefix character (@-:+!|).
jobPlan.quoteSystemdArgsfunctionno test imports itfunction quoteSystemdArgs(argv: readonly string[]): Result<string, ScheduleError>An argument vector as systemd's ExecStart= value, each word quoted by quoteSystemdArg; the first refusal names its index.
jobPlan.quoteCmdArgfunctionno test imports itfunction quoteCmdArg(arg: string, first?: boolean): Result<string, ScheduleError>One argument as a word of a line of a .cmd file that runs a program: as it is where it is plain, else in double quotes, inside which cmd.exe takes &|<>^() as text; %% for % (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, first, whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character but tab; and, for the program, an empty one. Expects delayed expansion off (the .cmd file turns it off), so ! is plain text.
jobPlan.quoteCmdArgsfunctionno test imports itfunction quoteCmdArgs(argv: readonly string[]): Result<string, ScheduleError>An argument vector as a command of a .cmd file, each word quoted by quoteCmdArg; the first refusal names its index.
jobPlan.JobOwnertypeno test imports ittype JobOwner = {
/** Lowercase labels of letters, digits and dashes, two or more, joined by dots (`org.example.backup`). */
readonly domain: string;
/** Letters, digits, dots, dashes and underscores, beginning and ending with a letter or digit (`Example`). */
readonly folder: string;
};Who a job belongs to: a reverse-DNS domain for the launchd label and the systemd unit, and a Task Scheduler folder.
jobPlan.JobSpectypeno test imports ittype JobSpec = {
/** Its name, unique under its owner. */
readonly name: JobName;
/** Its owner, which makes its l… (703 characters)type JobSpec = {
/** Its name, unique under its owner. */
readonly name: JobName;
/** Its owner, which makes its label and where its files go. */
readonly owner: JobOwner;
/** The program and its arguments, run without a shell (by the scheduler, or by the `.cmd` file on Windows). */
readonly argv: readonly string[];
/** The absolute folder it runs in. */
readonly workdir: string;
/** Variables added to its environment. */
readonly env?: Readonly<Record<string, string>>;
/** When it runs. */
readonly when: Schedule;
/** An absolute file its output and errors are appended to (systemd's journal, and nothing on macOS and Windows, without it). */
readonly log?: string;
};A job to schedule.
jobPlan.Targettypeno test imports ittype Target = { readonly os: SchedulerOs; readonly home: string; readonly uid?: number };The computer a job is planned for: its scheduler, the user's home folder in its own form, and on macOS the user's numeric id (launchctl's gui/<uid> domain).
jobPlan.PlannedFiletypeno test imports ittype PlannedFile = { readonly path: string; readonly content: string; readonly mode?: number };A file to write: its path relative to the home folder, parts joined by /; its text; and its mode where it matters (POSIX permission bits).
jobPlan.Steptypeno test imports ittype Step = { readonly argv: readonly string[]; readonly mayFail: boolean };A command to run, by its argument vector and never through a shell; mayFail where a failure is expected and stops nothing (nothing to unload).
jobPlan.JobPlantypeno test imports ittype JobPlan = {
/** The scheduler. */
readonly os: SchedulerOs;
/** The job's label: the systemd timer, the launc… (695 characters)type JobPlan = {
/** The scheduler. */
readonly os: SchedulerOs;
/** The job's label: the systemd timer, the launchd label, or the task's name. */
readonly label: string;
/** When it runs, in words. */
readonly description: string;
/** The files to write before `install`, and to remove after `remove`. */
readonly files: readonly PlannedFile[];
/** The commands that load and enable the job. */
readonly install: readonly Step[];
/** The commands that disable and unload it, before its files are removed. */
readonly remove: readonly Step[];
/** The commands to run once its files are removed (systemd forgets the units). */
readonly afterRemove: readonly Step[];
};What scheduling a job takes: the files to write, then install; to remove it, remove, then the files removed, then afterRemove.
jobPlan.planJobfunctionno test imports itfunction planJob(job: JobSpec, target: Target): Result<JobPlan, ScheduleError>What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.
SchedulerOstypetype SchedulerOs = "linux" | "darwin" | "windows";The schedulers a job can be planned for: systemd on Linux, launchd on macOS, Task Scheduler on Windows.
ScheduleErrortypetype ScheduleError = {
readonly kind: "schedule";
readonly field: string;
readonly reason: "invalid" | "unsafe";
readonly message: string;
};Why a job cannot be planned: the field at fault (name, argv[2], env.PATH, when.minute...), and whether its value is not valid or cannot be carried safely.
formatScheduleErrorfunctionfunction formatScheduleError(e: ScheduleError): stringA schedule error as one line: argv[1]: a line feed cannot be carried in a systemd unit.
JobNametypetype JobName = Brand<string, "JobName">;A job's name, safe in a file name, a unit name, a plist label and a task name: 1 to 64 lowercase letters, digits and dashes, beginning and ending with a letter or digit.
jobNamefunctionfunction jobName(s: string): Result<JobName, ScheduleError>A job's name, validated.
Weekdaytypetype Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";The day of a weekly schedule.
Whentypetype When =
| { readonly kind: "minutes"; readonly every: number }
| { readonly kind: "hourly"; readonly minute: num… (411 characters)type When =
| { readonly kind: "minutes"; readonly every: number }
| { readonly kind: "hourly"; readonly minute: number }
| { readonly kind: "daily"; readonly hour: number; readonly minute: number }
| { readonly kind: "weekly"; readonly day: Weekday; readonly hour: number; readonly minute: number }
| { readonly kind: "monthly"; readonly day: number; readonly hour: number; readonly minute: number };When a job runs, in local time: every N minutes on the clock, every hour at a minute, every day, every week on a day, or every month on a day.
Scheduletypetype Schedule = Brand<When, "Schedule">;A When whose numbers are in range, made only by schedule.
MINUTE_STEPSconstconst MINUTE_STEPS: readonly number[]The intervals minutes takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour.
schedulefunctionfunction schedule(when: When): Result<Schedule, ScheduleError>A schedule, validated: hours 0 to 23, minutes 0 to 59, a day of the month 1 to 28, a weekday by its three letters, a step of MINUTE_STEPS.
describeSchedulefunctionfunction describeSchedule(s: Schedule): stringWhen a schedule runs, as a sentence's end: every 15 minutes, every hour at minute 05, every day at 06:10, every Friday at 08:00, on day 3 of every month at 05:00.
onCalendarfunctionfunction onCalendar(s: Schedule): stringsystemd's OnCalendar= expression for a schedule (systemd.time(7)).
CalendarIntervaltypeno test imports ittype CalendarInterval = { readonly Minute: number; readonly Hour?: number; readonly Day?: number; readonly Weekday?: number };One launchd calendar interval: the job runs whenever every key given matches (Weekday 0 is Sunday).
calendarIntervalsfunctionfunction calendarIntervals(s: Schedule): readonly CalendarInterval[]launchd's StartCalendarInterval for a schedule: one interval, or one for each minute of the hour the job runs at.
schtasksSchedulefunctionfunction schtasksSchedule(s: Schedule): readonly string[]The arguments schtasks /Create takes for a schedule, from /SC on.
quoteSystemdArgfunctionno test imports itfunction quoteSystemdArg(arg: string, first?: boolean): Result<string, ScheduleError>One argument as a word of systemd's ExecStart= (systemd.service(5), "Command lines"): as it is where it is plain, else in double quotes with C escapes, %% for a specifier's % and $$ for a variable's $. Refused: NUL, a carriage return or a line feed; an argument that is only ; (a command separator); and, for the program (first), an empty one or one that begins with a prefix character (@-:+!|).
quoteSystemdArgsfunctionfunction quoteSystemdArgs(argv: readonly string[]): Result<string, ScheduleError>An argument vector as systemd's ExecStart= value, each word quoted by quoteSystemdArg; the first refusal names its index.
quoteCmdArgfunctionno test imports itfunction quoteCmdArg(arg: string, first?: boolean): Result<string, ScheduleError>One argument as a word of a line of a .cmd file that runs a program: as it is where it is plain, else in double quotes, inside which cmd.exe takes &|<>^() as text; %% for % (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, first, whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character but tab; and, for the program, an empty one. Expects delayed expansion off (the .cmd file turns it off), so ! is plain text.
quoteCmdArgsfunctionfunction quoteCmdArgs(argv: readonly string[]): Result<string, ScheduleError>An argument vector as a command of a .cmd file, each word quoted by quoteCmdArg; the first refusal names its index.
JobOwnertypeno test imports ittype JobOwner = {
/** Lowercase labels of letters, digits and dashes, two or more, joined by dots (`org.example.backup`). */
readonly domain: string;
/** Letters, digits, dots, dashes and underscores, beginning and ending with a letter or digit (`Example`). */
readonly folder: string;
};Who a job belongs to: a reverse-DNS domain for the launchd label and the systemd unit, and a Task Scheduler folder.
JobSpectypetype JobSpec = {
/** Its name, unique under its owner. */
readonly name: JobName;
/** Its owner, which makes its l… (703 characters)type JobSpec = {
/** Its name, unique under its owner. */
readonly name: JobName;
/** Its owner, which makes its label and where its files go. */
readonly owner: JobOwner;
/** The program and its arguments, run without a shell (by the scheduler, or by the `.cmd` file on Windows). */
readonly argv: readonly string[];
/** The absolute folder it runs in. */
readonly workdir: string;
/** Variables added to its environment. */
readonly env?: Readonly<Record<string, string>>;
/** When it runs. */
readonly when: Schedule;
/** An absolute file its output and errors are appended to (systemd's journal, and nothing on macOS and Windows, without it). */
readonly log?: string;
};A job to schedule.
PlannedFiletypeno test imports ittype PlannedFile = { readonly path: string; readonly content: string; readonly mode?: number };A file to write: its path relative to the home folder, parts joined by /; its text; and its mode where it matters (POSIX permission bits).
Steptypeno test imports ittype Step = { readonly argv: readonly string[]; readonly mayFail: boolean };A command to run, by its argument vector and never through a shell; mayFail where a failure is expected and stops nothing (nothing to unload).
JobPlantypetype JobPlan = {
/** The scheduler. */
readonly os: SchedulerOs;
/** The job's label: the systemd timer, the launc… (695 characters)type JobPlan = {
/** The scheduler. */
readonly os: SchedulerOs;
/** The job's label: the systemd timer, the launchd label, or the task's name. */
readonly label: string;
/** When it runs, in words. */
readonly description: string;
/** The files to write before `install`, and to remove after `remove`. */
readonly files: readonly PlannedFile[];
/** The commands that load and enable the job. */
readonly install: readonly Step[];
/** The commands that disable and unload it, before its files are removed. */
readonly remove: readonly Step[];
/** The commands to run once its files are removed (systemd forgets the units). */
readonly afterRemove: readonly Step[];
};What scheduling a job takes: the files to write, then install; to remove it, remove, then the files removed, then afterRemove.
planJobfunctionfunction planJob(job: JobSpec, target: Target): Result<JobPlan, ScheduleError>What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.