# Run your AI agent on a schedule with cron, and know when it fails

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-11-10
- Canonical (HTML): https://wurk.fun/blog/run-your-ai-agent-on-a-schedule-with-cron-and-know-when-it-fails
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/645f813b-5688-4737-babc-2423e7985fab/cover-cron.jpg?wurkUpload=v1.UsY9jHaduoMONPDNYJ1KHxCJ-1TV15tFmWXJX64ddXg

---

You built a small script that checks a job board, summarizes your mail, or posts a daily report. It works fine when you run it by hand. Then you get busy, the box reboots, an API hangs, and a week later you notice the report just quietly stopped. This post gives you the crontab line, the traps that break working scripts, logging, and a message to your phone when a run fails.

The whole setup is one crontab line that calls one wrapper script. The wrapper sets up the environment, runs your agent under a lock and a timeout, appends output to a dated log, records the last success, and sends you one message if the run fails. A second cron entry acts as a dead man's switch for the worst case: the whole box going quiet.

## The crontab line, field by field

Cron reads a per-user file (edit it with `crontab -e`) where each job is one line: five time-and-date fields, then the command ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)).

```
* * * * *  command
│ │ │ │ │
│ │ │ │ └─ day of week (0-7, 0 and 7 are both Sunday)
│ │ │ └─── month (1-12)
│ │ └───── day of month (1-31)
│ └─────── hour (0-23)
└───────── minute (0-59)
```

A field can be `*` (any value), a range like `8-11`, a list like `1,15`, or a step like `*/2` ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)). Three real lines:

```
# every day at 09:00
0 9 * * * /home/you/agent/run-agent.sh

# every 30 minutes
*/30 * * * * /home/you/agent/run-agent.sh

# Mondays at 06:15
15 6 * * 1 /home/you/agent/run-agent.sh
```

Two details worth knowing now: comments must sit on their own line, never after a job on the same line ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)), and the cron documented on that page (cronie) can syntax-check a file before you install it with `crontab -T`. Other cron versions, such as the one Debian and Ubuntu ship by default, may not have every option on that page, so check `man 5 crontab` on your own box. Also, the man page warns that during a daylight-saving shift, jobs in the missing hour never run and jobs in the repeated hour run twice ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)). Nothing to fix, just don't panic when it happens.

## Three traps that break a working script

**The environment is minimal.** Cron starts your job with only a few variables set up automatically: `SHELL` is `/bin/sh`, and `HOME` and `LOGNAME` come from your `/etc/passwd` line ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)). Whatever your interactive shell has in `PATH`, don't count on it. Set it at the top of the crontab:

```
PATH=/usr/local/bin:/usr/bin:/bin
```

Or call every binary by absolute path inside your scripts. `python3` resolving to a different install than the one you tested is the classic silent failure.

**Relative paths.** A script that works when you `cd` into the folder yourself can fail under cron because nothing has changed into that folder. Use absolute paths for every file, log, and binary, and if the agent needs to run from its own directory, do the `cd` inside the wrapper. Then the job behaves the same no matter what started it.

**The percent sign.** In the command field, an unescaped `%` is special: cron turns it into newlines and sends everything after it to the command as standard input ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)). So a `date +%F` typed directly into a crontab line breaks. Keep all logic in the wrapper script and the crontab line stays one clean command.

One more: the schedule is in the server's time zone, which on a VPS is often UTC, not yours. The same man page documents a `CRON_TZ` variable for giving one crontab its own time zone; again, check that your box's cron supports it ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)).

## Log every run

Cron throws away your script's output unless you send it somewhere. In the wrapper, append both standard output and standard error to a dated file; the man page's own example file uses exactly this shape, `>> $HOME/tmp/out 2>&1` ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)). The `2>&1` part sends error output to the same file. With a date in the filename you can answer "what did it print last Tuesday" without any tooling.

## Stop overlapping runs, then stop hangs

If a run can outlast its own interval, the next one starts on top of it and they fight over the same files. `flock -n` fixes that: it runs the command holding a lock on a file, and fails immediately instead of waiting if the lock is already taken ([flock(1)](https://man7.org/linux/man-pages/man1/flock.1.html)). The lock file is created if it doesn't exist ([flock(1)](https://man7.org/linux/man-pages/man1/flock.1.html)), so there is nothing to set up. When the lock is taken, `flock -n` exits with status 1 by default (`-E` changes it), so in the wrapper below a skipped run also triggers an alert. If runs overlap often, that alert is telling you the schedule is too tight.

The other failure mode is a run that never ends: an API that accepts the connection and never answers. `timeout 900 command` kills the command if it's still running after 900 seconds, sending TERM by default, and exits with status 124 on a timeout ([timeout(1)](https://man7.org/linux/man-pages/man1/timeout.1.html)). Adding `-k 30` sends an uncatchable KILL 30 seconds after the first signal if the process somehow ignored it ([timeout(1)](https://man7.org/linux/man-pages/man1/timeout.1.html)).

## Get told when it fails

The wrapper knows the exit code, so make it act on it. The simplest channel most people already have is a Telegram bot: the official Bot API's `sendMessage` method takes your bot token and a chat id ([Bot API docs](https://core.telegram.org/bots/api)). The wrapper below sends one short message with the exit code and the log path.

If you'd rather have zero code, cron can email you: set `MAILTO=you@example.com` in the crontab and cron mails you anything the job prints ([crontab(5)](https://man7.org/linux/man-pages/man5/crontab.5.html)).

Either way, keep the token or credentials out of the crontab itself. Put them in a small env file the wrapper sources, and lock it down:

```
chmod 600 /home/you/agent/.env
```

## The dead man's switch

A per-run alert covers the script failing. It does not cover cron itself dying, the box freezing, or the crontab getting wiped. For that, the wrapper touches a state file on every success, and a second cron job checks hourly whether that file is older than a threshold using `find -mmin`, and alerts if it is. It's a few lines, and it catches the failures the first alert can't.

## Copy-paste starter

The wrapper (`/home/you/agent/run-agent.sh`, `chmod +x`):

```bash
#!/bin/bash
# cron wrapper: lock, timeout, log, alert on failure
set -u

AGENT_DIR="/home/you/agent"
source "$AGENT_DIR/.env"          # TG_TOKEN, TG_CHAT_ID
mkdir -p "$AGENT_DIR/logs"
LOG="$AGENT_DIR/logs/$(date +%F).log"

echo "$(date '+%F %T') start" >> "$LOG"

if timeout -k 30 900 flock -n "$AGENT_DIR/.lock" "$AGENT_DIR/agent.sh" >> "$LOG" 2>&1; then
    touch "$AGENT_DIR/last_success"
    echo "$(date '+%F %T') ok" >> "$LOG"
else
    rc=$?
    echo "$(date '+%F %T') FAILED rc=$rc" >> "$LOG"
    curl -fsS "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
        -d chat_id="${TG_CHAT_ID}" \
        --data-urlencode "text=agent FAILED on $(hostname), rc=$rc, log: $LOG" \
        >> "$LOG" 2>&1 || true
fi
```

The watchdog (`/home/you/agent/watchdog.sh`):

```bash
#!/bin/bash
# alert if the last successful run is too old
set -u
source /home/you/agent/.env
STATE="/home/you/agent/last_success"

# alert if no success for 180 minutes (3 hours) - fits an hourly job;
# for a daily job use something like 1500 (25 hours)
if [ ! -f "$STATE" ] || [ -n "$(find "$STATE" -mmin +180)" ]; then
    curl -fsS "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
        -d chat_id="${TG_CHAT_ID}" \
        --data-urlencode "text=agent SILENT >3h on $(hostname)" \
        > /dev/null 2>&1 || true
fi
```

The crontab (`crontab -e`):

```
PATH=/usr/local/bin:/usr/bin:/bin

# your agent, every hour at minute 7
7 * * * * /bin/bash /home/you/agent/run-agent.sh

# dead man's switch, hourly at minute 47
47 * * * * /bin/bash /home/you/agent/watchdog.sh
```

Test both alerts once on purpose: temporarily make the agent script exit with `exit 1` for the failure alert, and fake an old timestamp with `touch -d '2 days ago' /home/you/agent/last_success` for the watchdog. Then screenshot this:

```
□ agent runs fine by hand, from an absolute path
□ PATH set at the top of the crontab, no inline comments after jobs
□ wrapper appends stdout AND stderr to a dated log
□ flock so runs never overlap, timeout so they never hang
□ secrets in a chmod 600 env file, not in the crontab
□ failure alert tested once on purpose
□ dead man's switch tested once on purpose
```

Set it up once and the report shows up on its own, and when something breaks you hear about it on the next run, not a week later.

If your agent calls APIs, pair this with [Put a timeout on every tool call your AI agent makes](https://wurk.fun/blog/put-a-timeout-on-every-tool-call-your-ai-agent-makes), so one slow call can't eat the whole run.

If this saved you some debugging time, a small tip on the post is appreciated.
