Scheduling Jobs with cron and Timers
Cron syntax
┌ minute (0-59)
│ ┌ hour (0-23)
│ │ ┌ day of month (1-31)
│ │ │ ┌ month (1-12)
│ │ │ │ ┌ day of week (0-6, Sunday = 0)
│ │ │ │ │
30 2 * * * /usr/local/bin/pg-backup.sh
| Expression | Runs |
|---|---|
*/5 * * * * |
every 5 minutes |
0 * * * * |
every hour on the hour |
0 9 * * 1-5 |
09:00 on weekdays |
0 0 1 * * |
midnight on the 1st of each month |
Edit your jobs with crontab -e; list them with crontab -l. Use the Cron Parser in Dev Tools to check an expression before you rely on it.
The three cron pitfalls
- A minimal environment. Cron does not load your
.bashrc, soPATHis short and your variables are missing. Use full paths and load config explicitly. - Silent failures. Output goes to local mail nobody reads. Redirect it to a log.
- Overlapping runs. A slow job can still be running when the next one starts.
A robust entry that solves all three:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
30 2 * * * flock -n /tmp/backup.lock /usr/local/bin/pg-backup.sh >> /var/log/backup.log 2>&1
flock -n skips the run if the previous one still holds the lock.
Know when a job did not run
A failed job is visible; a job that silently stopped running is not. Use a dead man's switch such as Healthchecks.io or Better Stack heartbeats: the script pings a URL at the end, and you are alerted if the ping does not arrive on time.
/usr/local/bin/pg-backup.sh && curl -fsS -m 10 --retry 3 https://hc-ping.com/your-uuid > /dev/null
Timers instead of cron
On systemd servers, timers (see Linux System Administration) give you journalctl logs per run, Persistent=true catch-up after downtime and resource limits. Prefer them for important jobs.
Scheduling in the cloud
On platforms like Render, use Cron Jobs as a separate service with the same code and env vars as your app. Keep scheduled work out of web workers, which can be restarted or scaled at any time.
Exercise
Schedule your disk-alert script to run every 15 minutes with flock, logging to a file, and a heartbeat ping on success.
I tuoi progressi sono salvati solo in questo browser.
Invia per la revisione (10 punti)