Retry a failed cron job automatically, without hiding the failure
The retry loop everyone posts runs once under cron's /bin/sh and exits 0. A wrapper that keeps the exit code, plus what curl and systemd retries did in our tests.
9 min read
The job failed at 03:00 because the API was down for a minute. Nothing ran it again, so the feed
was stale until 03:00 the next day. Cron has no retry setting, so you search for one and find a
for loop on Stack Overflow.
We ran that loop under Debian 13 cron, then tested a wrapper that keeps the exit code. We also tried the retries built into curl and systemd. RunWisp’s are at the end.
debian 13 cron · bash 5.2 · curl 8.18 · systemd 257 · job exits 7
- for i in {1..5}1 attempt under cron, exit 0
- same loop, bash5 attempts, still exit 0
- --retry-max-time 4curl call ran for 7.0 s
- RestartSec=3default start limit never stopped it
- runwisp retrieseach attempt its own run and exit code
Short answer
Cron starts the command once per schedule and ignores its exit code. To retry, wrap the command in a script that tries again with a growing pause and exits with the last attempt’s exit code, so cron mail or a heartbeat check still sees the failure:
0 3 * * * /usr/local/bin/retry 4 30 timeout 10m /usr/local/bin/publish.sh
The script is below. Only retry work that is safe to
run twice, and keep the worst case (attempts × timeout, plus the waits) shorter than the schedule
interval. If the job is one HTTP call, curl -f --retry does it alone. On a systemd timer, put
Restart=on-failure on the service. RunWisp, an open-source cron replacement that ships as a single
binary, has retry_attempts on each task and keeps every attempt’s output in its run history.
The retry loop everyone posts
This is the loop in most answers, here with a test job that always fails with exit code 7:
for i in {1..5}; do job && break || sleep 5; done
What it did:
| Shell | Where you get it | Attempts | Exit code |
|---|---|---|---|
| dash 0.5.12 | Debian 13 /bin/sh, so Debian cron |
1 | 0 |
| BusyBox sh | Alpine 3.22 /bin/sh and crond |
1 | 0 |
| bash 5.2 (Debian 13) | your terminal, or SHELL=/bin/bash |
5 | 0 |
| Debian 13 cron, for real | * * * * * line in /etc/cron.d |
1 | 0 |
Two separate bugs. {1..5} is bash brace expansion. Cron runs commands with /bin/sh, which
doesn’t have it, so the loop gets a single word, {1..5}, and runs one time. You only see five
attempts when you test it in a bash prompt.
The second bug is in every shell. job && break || sleep 5 means “if the job fails, sleep”. On the last attempt the job fails and sleep runs. sleep succeeds, so the loop’s exit code is 0.
Five failures in a row look like a clean run to anything that checks the exit code.
A retry wrapper that keeps the exit code
Save as /usr/local/bin/retry and chmod +x it:
#!/bin/sh
# usage: retry ATTEMPTS DELAY COMMAND [ARGS...]
attempts=$1 delay=$2
shift 2
n=1
while :; do
"$@" && exit 0
rc=$?
[ "$n" -ge "$attempts" ] && exit "$rc"
echo "retry: attempt $n of $attempts exited $rc, next in ${delay}s" >&2
sleep "$delay"
n=$((n + 1))
delay=$((delay * 2))
done
- It’s plain
shwith no bash features. We ran it under the same shells as the loop above. rc=$?right after"$@" && exit 0is the command’s exit code, not the loop’s, and the last failure leaves with it. A job that exited 7 three times makesretryexit 7.- The delay doubles:
retry 4 30waits 30, 60 and 120 seconds between four attempts. - The
retry:lines go to stderr, so they end up wherever the job’s own errors go: cron mail, or a log file if you redirect2>&1.
A job that failed twice and then worked:
$ retry 4 1 ./flaky
flaky: try 1
retry: attempt 1 of 4 exited 7, next in 1s
flaky: try 2
retry: attempt 2 of 4 exited 7, next in 2s
flaky: try 3
$ echo $?
0
Put timeout between retry and the job, as in the cron line above. Without it, an attempt that
hangs never fails, and retry waits on it forever. More on that in
how to kill a cron job that runs too long.
Is the job safe to run twice?
A retry runs the job again after it reported a failure. That doesn’t mean the first attempt did nothing.
In our curl tests, the client gave up on a slow request after 3 seconds and retried. The server kept working on each request and finished it after 10 seconds. Every “failed” attempt did the work. If that request had sent an email or charged a card, each retry would have done it again.
Safe to retry as is:
- Copies that overwrite:
rsync, or a download to a temp file followed bymv. - Writes that ignore duplicates, like
INSERT … ON CONFLICT DO NOTHING, or an API call with an idempotency key.
Not safe without changes:
- Sending mail or charging money, and any API call that creates something.
- Appending to a file or a table with no way to spot the duplicate.
For the second group, make the job record what it finished and skip it next time, or don’t retry it and send an alert instead. The failure alerts post covers that side.
Retries and the next scheduled run
The worst case for a retry chain is every attempt running to its timeout, plus the waits. A job
every 15 minutes with retry 4 30 timeout 3m can run 4 × 3 minutes plus 30 + 60 + 120 seconds:
15.5 minutes. The next run starts at minute 15 while the chain is still on its last attempt, and
cron happily runs both.
Either shrink the numbers until the sum fits, or add a lock so a second copy exits at once:
*/15 * * * * flock -n /run/lock/publish.lock /usr/local/bin/retry 4 30 timeout 3m /usr/local/bin/publish.sh
Preventing cron job overlap has the details on flock.
curl retries on its own
If the job is one HTTP request, curl’s --retry is enough. What curl 8.18 did against a local test
server, with --retry 2:
| Response | Retried? | Exit code |
|---|---|---|
503, without -f |
yes, 3 attempts | 0 |
503 or 500, with -f |
yes, 3 attempts | 22 |
404, with -f |
no | 22 |
| Connection refused | no, unless --retry-connrefused |
7 |
Timeout from --max-time 3 |
yes | 28 |
The first row is the one that bites. Without -f, curl treats any HTTP response as success, so it
retried a 503 three times and then told cron everything was fine. The manual’s list of retried
errors is timeouts plus HTTP 408, 429, 500, 502, 503, 504, 522 and 524.
The time limits are easy to misread:
--max-timelimits each attempt. It starts over on every retry.--retry-max-timeis only checked before a new attempt starts. It doesn’t stop one that’s running. With--max-time 3 --retry 5 --retry-max-time 4, the call ran for 7.0 seconds: two attempts of 3 seconds and a 1 second wait (we set--retry-delay 1). Without--retry-max-timeit ran all six attempts, 23 seconds.
A line that fails loudly:
*/15 * * * * curl -fsS --retry 4 --retry-connrefused --max-time 30 -o /dev/null https://example.com/refresh
systemd timers: Restart=on-failure
A timer starts a service, and the service can restart itself on failure. That works with
Type=oneshot; we tested systemd 257 on Debian 13:
# /etc/systemd/system/publish.service
[Unit]
StartLimitIntervalSec=10min
StartLimitBurst=4
[Service]
Type=oneshot
ExecStart=/usr/local/bin/publish.sh
TimeoutStartSec=3min
Restart=on-failure
RestartSec=30s
A test job that failed twice and then worked shows up in the journal like this:
flaky[93]: flaky: try 1
systemd[1]: fetch.service: Main process exited, code=exited, status=7/NOTRUNNING
systemd[1]: fetch.service: Scheduled restart job, restart counter is at 1.
flaky[98]: flaky: try 2
systemd[1]: fetch.service: Scheduled restart job, restart counter is at 2.
flaky[102]: flaky: try 3
systemd[1]: fetch.service: Deactivated successfully.
The attempt count comes from the start limit, and both of its numbers matter:
- Too loose, and it never gives up. The default is 5 starts in 10 seconds. With
RestartSec=3, a service that always fails never fits 5 starts into 10 seconds. Ours restarted 7 times in 25 seconds and was still going when we stopped it. - Too long, and it blocks the next run.
StartLimitBurst=3withStartLimitIntervalSec=1hgave three attempts, as intended. Starting the service again right after was refused withStart request repeated too quickly, and a timer start inside that hour would be too.
So set StartLimitBurst to the number of attempts you want, and StartLimitIntervalSec longer than
the retry chain but shorter than the timer interval. RestartSec is fixed; on systemd 254 and newer,
RestartSteps= and RestartMaxDelaySec= make it grow.
If the service has an OnFailure= alert, it fires after every failed attempt, not once per chain.
systemd timer email on failure shows the fix
(RestartMode=direct).
Retries with a run history
The wrapper and systemd both leave you reading text to find out what happened. A night with two
failed attempts and a good third one is three retry: lines in a mail, or a handful of journal
lines. The exit code says the job worked, and that’s all most checks look at.
RunWisp is an open-source cron replacement that ships as a single binary. Retries are settings on the task:
[tasks.publish-feed]
cron = "*/15 * * * *"
run = "/usr/local/bin/publish.sh"
timeout = "3m"
retry_attempts = 3 # extra tries after the first
retry_delay = "30s"
retry_backoff = "exponential" # waits 30s, 60s, 120s
Every attempt is its own run in the history, with its own exit code and log, numbered and linked to
the attempt before it. On RunWisp 1.10.0, our test task that failed twice (with retry_delay = "2s")
looked like this:
| Started | Attempt | Result | Exit code |
|---|---|---|---|
| 16:09:58 | 0 | failed | 7 |
| 16:10:00 | 1 | failed | 7 |
| 16:10:04 | 2 | succeeded | 0 |
The failed attempts keep their output, so you can read why the API was down at 03:00 even though the
feed got published. timeout applies to each attempt, and failure alerts for repeated attempts are
grouped, so a chain usually sends one message instead of three.
The limits: a run is retried only when the task’s failures setting counts it as a failure, and no
wait is longer than 5 minutes. The worst-case sum from above
applies here too, since scheduled runs keep their times while a chain waits. RunWisp can’t know
whether your job is safe to run twice, and it covers one host. If you don’t need the history, the
wrapper above does the retrying on its own.
Common questions
How do I retry a failed cron job automatically?
Why does my for i in {1..5} retry loop only run once in cron?
Does cron retry a job that fails?
How do I make curl retry in a cron job?
Can a systemd timer retry a failed service?
Is there a cron replacement with built-in retries?
Read next
-
Cron pipeline exits 0 when pg_dump fails: pipefail and empty backups
pg_dump | gzip in cron reported success while the database was down and left a 20-byte backup. What pipefail fixes, where /bin/sh lacks it, and what it doesn't fix.
-
List all cron jobs for all users on Linux, including the ones crontab -l misses
The usual crontab -l -u loop found 2 of the 9 cron lines on our Debian 13 test box. Where cron jobs actually live on each distro, a script that lists every one with its owner, and the crontab userdel -r leaves behind.