Skip to content

Scripts and cron

Anything that runs on a schedule can tell you how it went. These use an API Source: create one in the app, choose API, and copy its key.

Put the key in the environment instead of the script, for example in a file only you can read, which the script sources:

Terminal window
export POCKETBELL_KEY=pb_live_…

Then, at the end of a script:

Terminal window
curl -fsS https://api.pocketbell.dev/v1/messages \
-H "Authorization: Bearer $POCKETBELL_KEY" \
-H "Content-Type: application/json" \
-d '{"title": "Backup finished", "message": "db-1 is backed up."}'

Wrap the job, and send a Critical notification when it exits with an error:

#!/bin/sh
# pocketbell-run: runs a command, and tells Pocketbell if it fails.
"$@" && exit 0
status=$?
jq -n --arg title "Failed: $1" --arg message "Exit status $status on $(hostname)" \
'{title: $title, message: $message, priority: "critical", tags: ["cron"]}' |
curl -fsS https://api.pocketbell.dev/v1/messages \
-H "Authorization: Bearer $POCKETBELL_KEY" \
-H "Content-Type: application/json" \
--data @-
exit $status

Save it as /usr/local/bin/pocketbell-run, make it executable with chmod +x, and put it in front of the job in the crontab:

0 3 * * * POCKETBELL_KEY=pb_live_… /usr/local/bin/pocketbell-run /usr/local/bin/backup.sh

jq --arg makes each value a JSON string, so a name with quotes in it can’t break the request. Critical notifications repeat until you acknowledge them; see Critical notifications.

To know when a job doesn’t run at all, pair this with a heartbeat service, such as Healthchecks.io.

With Requests:

import os
import requests
requests.post(
"https://api.pocketbell.dev/v1/messages",
headers={"Authorization": f"Bearer {os.environ['POCKETBELL_KEY']}"},
json={"title": "Import finished", "message": "4,210 rows in 38 s"},
timeout=10,
).raise_for_status()

json= builds the body and sets the content type.

If your script retries on a network error, send an Idempotency-Key header with a value that’s the same for every try, such as the job’s name and date. A retry with the same key doesn’t notify you twice. See Send a notification.