ToolBoxOnline
Developer

Scheduling Database Backups With Cron (And Checking the Expression Before It Runs)

You set a cron job to back up your database at 2am. It never ran. Here's how to write and verify cron expressions for backups and maintenance.

crondatabase backupcron expressionserver maintenancescheduling

You add a cron job to back up your database every night at 2am. The next morning you check: nothing ran. You look at the expression you wrote — 0 2 * * * — and it looks right. But it was 2pm, not 2am. A twelve-hour mistake that cost you a night of backups. Cron expressions are compact and unforgiving, and the wrong one fails silently. That's why you verify the expression before you deploy it, with a cron parser.

Reading a Cron Expression in Five Fields

A cron expression has five fields: minute, hour, day of month, month, day of week. 0 2 * * * means "at minute 0 of hour 2, every day" — 2:00am. 30 3 * * 1 means "at 3:30am on Mondays only." */15 * * * * means "every 15 minutes."

The trap is that day-of-month and day-of-week combine with OR logic in most cron implementations. 0 2 1 * 1 runs on the first of the month AND on every Monday — not on Mondays that happen to be the first. That's the counter-intuitive part that catches everyone eventually.

Scheduling a Database Backup You Can Trust

Step 1: Pick a time when traffic is low. For most small sites, 2-3am works. Avoid the top of the hour if your host's other tenants also back up at :00 — a busy disk slows the job. Step 2: Write the expression and check it. Paste it into the cron parser and confirm the next run times match what you intend. The parser shows the next five occurrences, so a wrong hour jumps out immediately. Step 3: Add logging. Redirect the job output to a file so you can see when it runs: 0 2 * * * /backup.sh >> /var/log/backup.log. The text diff tool is handy when you compare two versions of a crontab file to spot what changed after an edit.

Step 4: Verify the day-of-week logic. The common mistake is assuming day-of-month and day-of-week mean AND. If you write 0 2 15 * 5 expecting "the 15th when it's a Friday," you actually get "the 15th OR any Friday" — about four times more often than you intended. The parser's occurrence list shows this immediately.

The counter-intuitive tip: test the backup script by hand first, then schedule it. A cron job can't fix a script that fails on its own. Run bash /backup.sh, confirm the dump file exists, then wire up the schedule. The Unix timestamp tool helps you check timezone math when your server runs in UTC but you think in local time — 2am local might be 18 2 * * * or worse. For the fundamentals of cron syntax, read our guide to crontab schedules. When your expression is ready, our cron parser validates it before it ever goes live.

Tools mentioned in this article

Compartir esta herramienta