Recover missed scheduled jobs on a cloud Mac
The script that summarizes build results overnight produced no daily report, yet it ran successfully when started manually the next day. The problem is usually not the calculation itself, but the assumption that “started on schedule” means “completed for the day.” For daily statistics, artifact inventories, and similar jobs on a cloud Mac, have the scheduler repeatedly invoke a reconciler. Persistent state should determine which dates still need processing.
Define the business date and completion criteria first
This article processes completed UTC calendar days: today is excluded, while yesterday and earlier dates can be caught up. The example writes daily build counts to SQLite, makes no network requests, and does not depend on a graphical session. Python 3 must be installed. Each dated file in the input directory must contain a single nonnegative integer representing the number of builds that day.
Completion does not mean that the script has exited. It means that the result for a date and the completion checkpoint have been committed in the same transaction. The checkpoint records the last day in an unbroken sequence of completed days; a missing day cannot be skipped.
The timer only provides opportunities to run. A missed trigger is recoverable. Incorrectly marking a failed date as complete is what creates a permanent gap.
If your business uses local calendar dates, define the time zone and daylight saving rules separately. Do not reuse the UTC boundaries below unchanged.
Build a daily reconciler with rollback support
First, create a directory and an isolated Python environment under a dedicated task account:
mkdir -p "$HOME/daily-reconcile/input"
cd "$HOME/daily-reconcile"
python3 -m venv .venv
Save the following as reconcile.py in that directory. The first run requires a start date. Keep passing the same date on subsequent runs; it will not overwrite an existing checkpoint.
import argparse
import sqlite3
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--start", type=date.fromisoformat, required=True)
args = parser.parse_args()
root = Path(__file__).resolve().parent
yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)
if args.start > yesterday:
raise SystemExit("Start date must be before today")
db = sqlite3.connect(root / "state.sqlite3", timeout=30)
try:
with db:
db.execute(
"CREATE TABLE IF NOT EXISTS progress "
"(id INTEGER PRIMARY KEY CHECK(id=1), last_day TEXT NOT NULL)"
)
db.execute(
"CREATE TABLE IF NOT EXISTS daily "
"(day TEXT PRIMARY KEY, builds INTEGER NOT NULL)"
)
db.execute(
"INSERT OR IGNORE INTO progress VALUES (1, ?)",
((args.start - timedelta(days=1)).isoformat(),)
)
while True:
try:
db.execute("BEGIN IMMEDIATE")
last = date.fromisoformat(
db.execute(
"SELECT last_day FROM progress WHERE id=1"
).fetchone()[0]
)
day = last + timedelta(days=1)
if day > yesterday:
db.rollback()
break
raw = (root / "input" / f"{day.isoformat()}.txt").read_text()
count = int(raw.strip())
if count < 0:
raise ValueError("Build count must be nonnegative")
db.execute(
"INSERT INTO daily VALUES (?, ?)",
(day.isoformat(), count)
)
db.execute(
"UPDATE progress SET last_day=? WHERE id=1",
(day.isoformat(),)
)
db.commit()
except BaseException:
db.rollback()
raise
finally:
db.close()
Each transaction commits just one day. A missing file, invalid content, or a failed write stops the current run. Previously completed days remain intact, and the next run retries the failed date. With BEGIN IMMEDIATE, concurrent instances acquire the write lock before reading the checkpoint. An instance can exit with an error if waiting for the lock times out, then try again on the next trigger.
The producer should write each input to a temporary file in the same directory and then rename it atomically. This prevents the reconciler from reading a partially written number.
Use launchd for recurring attempts, not a single trigger
For the test, first generate yesterday’s input. In production, these files should come from your statistics workflow; do not treat the test count as real data.
.venv/bin/python - <<'PY'
from datetime import datetime, timezone, timedelta
from pathlib import Path
day = datetime.now(timezone.utc).date() - timedelta(days=1)
Path("input", f"{day.isoformat()}.txt").write_text("12\n")
Path("start-day.txt").write_text(day.isoformat())
PY
Generate the configuration in the same directory. The interpreter path is taken from the actual virtual environment rather than assuming where Python is installed:
.venv/bin/python - <<'PY'
import plistlib
import sys
from pathlib import Path
root = Path.cwd()
target = Path.home() / "Library/LaunchAgents/com.scriptmac.daily-reconcile.plist"
target.parent.mkdir(parents=True, exist_ok=True)
config = {
"Label": "com.scriptmac.daily-reconcile",
"ProgramArguments": [
sys.executable,
str(root / "reconcile.py"),
"--start",
(root / "start-day.txt").read_text().strip()
],
"RunAtLoad": True,
"StartInterval": 900,
"StandardOutPath": str(root / "stdout.log"),
"StandardErrorPath": str(root / "stderr.log")
}
target.write_bytes(plistlib.dumps(config))
PY
plutil -lint "$HOME/Library/LaunchAgents/com.scriptmac.daily-reconcile.plist"
launchctl bootstrap "gui/$(id -u)" \
"$HOME/Library/LaunchAgents/com.scriptmac.daily-reconcile.plist"
This LaunchAgent depends on the account’s graphical login session. It is not a service that runs unconditionally after the machine boots. If the GUI domain does not exist, log in to the appropriate session before loading it. Production jobs that must run with no user logged in need a separately configured system-level LaunchDaemon, with an explicit execution user and directory permissions.
Fifteen minutes is a retry opportunity, not a guarantee of punctual execution. After the session resumes or the job is reloaded, the reconciler still uses the database to catch up on outstanding dates.
Use fault injection to verify recovery
Run the script manually first, then query the results:
.venv/bin/python reconcile.py --start "$(cat start-day.txt)"
sqlite3 state.sqlite3 \
'SELECT * FROM daily; SELECT * FROM progress;'
Run it twice in succession. The daily table should still contain only one row for yesterday. Next, in a separate test directory, move the start date back by two days and provide only the first day’s file. Execution should stop on the second day, leaving the checkpoint at the first day. Add the missing files and run it again: processing should advance rather than repeat the first day.
Then change an input to a negative number and confirm that no result is stored for the failed date. To test an interrupted transaction, temporarily inject a failure after the checkpoint update but before the commit. Verify that both the result and the checkpoint are rolled back. Do not merely check the logs for errors; verify that the dates in the database form an unbroken sequence.
Keep external side effects within explicit boundaries
The example’s atomicity covers only the same database. If you send a notification inside the transaction before committing the checkpoint, the process could exit between those steps, causing the notification to be sent again on retry. If you commit the checkpoint first and send afterward, the notification might never be sent.
In production, you can write pending events to a transactional outbox alongside the daily results, using “task name plus business date” as the unique key, and let a consumer retry delivery. The receiver must still support idempotent processing. An outbox alone cannot prevent duplicate delivery when sending succeeds but the acknowledgment is lost.
Finish with three acceptance criteria: the checkpoint covers a continuous sequence of dates, failed dates are not committed, and reruns do not add duplicate results. If historical inputs can be revised, provide an explicit recalculation workflow rather than silently moving the checkpoint backward. Back up the state database regularly and monitor how many days the checkpoint is behind. If the database is lost, do not simply restart from today without a review.
Frequently asked questions
Why keep a checkpoint if launchd starts the job?
Starting a process does not prove a business date was processed. Read the last completed date, process each day through yesterday, and advance the checkpoint only when results commit.
Does a SQLite transaction make notification delivery exactly once?
No. It only commits changes atomically within the same database. External delivery needs an idempotency key or a transactional outbox with a retrying consumer.
Choose a dedicated cloud Mac for your build workload
Match the chip, memory, SSD, and rental term to your workload. Each physical machine is assigned to one customer; check the console for real-time availability.