VPS Tutorials
Schedule VPS jobs with cron and systemd timers: logs and safe backups
Configure cron expressions and systemd timers with explicit timezones, paths, logs and locks. Handle missed runs, failures and notifications, and schedule database backups, log rotation, containers and WordPress reliably.

Database backups, log retention, data synchronization and certificate renewal all need a scheduler you can observe. Linux commonly offers cron and systemd timers. This guide explains configuration; use the separate scheduled-task troubleshooting checklist when an existing task fails to run.
| Requirement | cron | systemd timer |
|---|---|---|
| Configuration | Usually one schedule line | A service and timer pair |
| Syntax | Five time fields | Calendar or monotonic expressions |
| Logs | Redirect output or configure mail | Service output normally enters the journal |
| Missed calendar runs | Normally skipped | Can coalesce a missed run with Persistent=true |
| Overlap | Add a shared lock | Does not start another instance of the same active service |
| Dependencies | Handle in the job | Unit ordering/requirements, such as After= and Requires= |
| Timing | Minute-based, not a hard real-time guarantee | Default accuracy window is usually one minute |
| Containers | Requires a scheduler process | Requires an appropriate systemd environment |
- Simple periodic jobs: cron is often sufficient.
- Jobs needing journal logs, dependency management or missed-run handling: consider a timer.
- Machines that are often off:
Persistent=truecan help with calendar jobs, subject to timer behavior. - Container workloads: consider host scheduling with
docker exec, an application scheduler or a dedicated job container.
Use the simplest scheduler that meets the job's reliability requirements; running cron in a deliberately managed container is possible, but its process/log lifecycle must be designed.
┌─── 分钟 (0-59)
│ ┌─── 小时 (0-23)
│ │ ┌─── 日期 (1-31)
│ │ │ ┌─── 月份 (1-12)
│ │ │ │ ┌─── 星期 (0-7,0 和 7 都是周日)
│ │ │ │ │
* * * * * 要执行的命令
The fields are minute 0–59, hour 0–23, day of month 1–31, month 1–12 and weekday 0–7; 0 and 7 normally mean Sunday. A user crontab then contains the command.
| Expression | Meaning in the scheduler's timezone |
|---|---|
0 3 * * * | Daily at 03:00 |
*/15 * * * * | Every 15 minutes |
0 */6 * * * | At 00:00, 06:00, 12:00 and 18:00 |
30 2 * * 0 | Sunday at 02:30 |
0 4 1 * * | First day of each month at 04:00 |
0 9-18 * * 1-5 | Every hour from 09:00 through 18:00, weekdays |
15 2 * * 1,3,5 | Monday, Wednesday and Friday at 02:15 |
Useful shortcuts:
@daily /srv/scripts/backup.sh # 等于 0 0 * * *
@hourly /srv/scripts/sync.sh # 等于 0 * * * *
@weekly /srv/scripts/cleanup.sh # 等于 0 0 * * 0
@reboot /srv/scripts/startup.sh # 开机后执行一次
@reboot is a startup trigger, not a supervised long-running service or a dependency guarantee. Exact daemon restart behavior varies by cron implementation. Use a proper unit for an application that must remain running; see systemd service troubleshooting.
In common Vixie-style cron, when both day fields are restricted, either matching one triggers the job:
0 0 13 * 5 # 每月 13 号执行,「或者」每周五执行
This illustrative line lacks a command and is not a complete runnable entry. To require the 13th and Friday, test the weekday inside the job:
0 0 13 * * [ "$(date +\%u)" = "5" ] && /srv/scripts/task.sh
The \% escape is needed in a crontab line. Check your scheduler's semantics rather than applying this rule to every cron-like system.
An unescaped % is special to cron: it ends the command segment and supplies following text on standard input. This example is intentionally wrong:
# ❌ 错误:% 被当成换行符,命令会被截断
0 3 * * * tar czf /backup/$(date +%F).tar.gz /srv/app
Escape it with \%:
# ✅ 正确
0 3 * * * tar czf /backup/$(date +\%F).tar.gz /srv/app
A clearer default is to put the command in a script and schedule that script. % inside the script does not need cron-specific escaping. Shell quoting alone does not remove cron's percent handling.
cron does not load your interactive SSH shell. PATH may be as small as /usr/bin:/bin, leading to command not found for commands that work interactively.
# 1. 脚本里用绝对路径(最稳)
/usr/bin/docker compose -f /srv/app/compose.yml up -d
# 2. crontab 顶部设 PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 3 * * * docker compose -f /srv/app/compose.yml up -d
# 3. 脚本开头 source 环境(依赖 shell 配置,最不稳)
Use verified absolute paths; which docker or command -v docker helps locate the executable. An explicit PATH is another option. Sourcing interactive profiles is fragile, especially with nvm/pyenv. Set the working directory and required non-secret variables deliberately, and read secrets from an appropriately protected source.
Some cron installations mail output if a mail transport exists; otherwise it may be discarded or logged as undeliverable. Local mail may accumulate under /var/mail/.
# ✅ 正常输出和错误都写进日志
0 3 * * * /srv/scripts/backup.sh >> /var/log/backup.log 2>&1
# 只要错误,成功时不记
0 3 * * * /srv/scripts/backup.sh > /dev/null
# ❌ 全部丢弃 —— 出错了你永远不知道
0 3 * * * /srv/scripts/backup.sh > /dev/null 2>&1
Put 2>&1 after >> so stderr follows the already redirected stdout. 2>&1 >> file copies the old stdout destination first, so errors go elsewhere. Keeping only stderr can be intentional, but discarding everything hides failures. Ensure the task user can write the log and configure rotation.
crontab -e # 编辑当前用户的
crontab -l # 查看
crontab -r # 删除全部(危险,没有二次确认)
sudo crontab -e # 编辑 root 的
sudo crontab -u www-data -e # 编辑指定用户的
crontab -r can remove the entire table without the expected confirmation. Save it first with crontab -l > ~/crontab.bak. crontab -e and sudo crontab -e edit different users' tables.
System files use another format:
# /etc/cron.d/backup —— 注意这里多一个「用户」字段
0 3 * * * root /srv/scripts/backup.sh >> /var/log/backup.log 2>&1
Files in /etc/cron.d/ include a username after the time fields; entries edited through crontab -e do not. Check root ownership, allowed filename conventions and a final newline for the installed cron implementation.
The .service describes the work; .timer describes the trigger. Example service at /etc/systemd/system/backup.service:
[Unit]
Description=Daily backup job
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=root
ExecStart=/srv/scripts/backup.sh
Use the least-privileged task account when root is unnecessary. Network ordering helps only when the relevant online-wait service participates; the job still needs bounded retries for real dependencies.
Timer at /etc/systemd/system/backup.timer:
[Unit]
Description=Run backup daily at 3am
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
Enable the timer:
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
Enable .timer, not the associated .service as a boot job. The matching filename normally selects the service; Unit= can choose another.
The source notation 星期 年-月-日 时:分:秒 means weekday, year-month-day and hour:minute:second; weekday can be omitted.
| Expression | Meaning |
|---|---|
*-*-* 03:00:00 | Daily at 03:00 |
*-*-* *:00:00 | Every hour |
*-*-* *:00/15:00 | Every 15 minutes |
Mon *-*-* 02:30:00 | Monday at 02:30 |
*-*-01 04:00:00 | First day of the month at 04:00 |
Mon..Fri *-*-* 09:00:00 | Weekdays at 09:00 |
*-01,04,07,10-01 00:00:00 | First day of each quarter |
| Shortcut | Equivalent expression |
|---|---|
minutely | *-*-* *:*:00 |
hourly | *-*-* *:00:00 |
daily | *-*-* 00:00:00 |
weekly | Mon *-*-* 00:00:00 |
monthly | *-*-01 00:00:00 |
yearly | *-01-01 00:00:00 |
quarterly | *-01,04,07,10-01 00:00:00 |
Validate expressions and inspect future times:
systemd-analyze calendar "Mon..Fri *-*-* 09:00:00" --iterations=3
Confirm the timezone and DST behavior; a correct expression can still represent the wrong business time.
Persistent=truerecords calendar-trigger state. If a run was missed while inactive, activation can trigger one catch-up run, not replay every missed interval. Randomized delay may still apply.RandomizedDelaySec=300adds a delay of up to 300 seconds to distribute load across jobs/servers.AccuracySec=normally defaults to one minute to coalesce wakeups. A smaller window is possible:
[Timer]
OnCalendar=*-*-* 03:00:00
AccuracySec=1s
AccuracySec=1s does not promise hard real-time execution: system load, clock synchronization and other delays still matter.
# 列出所有定时器,包括下次触发时间和上次执行时间
systemctl list-timers --all
# 只看某一个
systemctl list-timers backup.timer
# 看执行日志(这是 systemd timer 最大的好处)
journalctl -u backup.service -n 50 --no-pager
# 手动触发一次测试(不用等到点)
sudo systemctl start backup.service
systemctl list-timers shows NEXT and LAST, but a trigger timestamp is not proof that the work succeeded. Inspect the service exit status and output. Manually starting the service executes the real task; test safely with representative inputs.
#!/usr/bin/env bash
set -euo pipefail
-eexits on certain unhandled failures, with important conditional/context exceptions.-urejects unintended unset variables.-o pipefailmakes a failed pipeline stage affect the pipeline status.
For example, without correct pipeline handling, mysqldump can fail while gzip creates a valid-looking empty compressed file. These options help but do not replace explicit checks, traps and restore testing. Use Bash for this example; not every /bin/sh supports pipefail.
# ❌ 依赖当前目录和 PATH
cd app && ./backup.sh
# ✅
cd /srv/app || exit 1
/usr/bin/mysqldump ...
Ellipses are placeholders, not runnable dump arguments. Set the account, credentials, destination and permissions deliberately.
Two rsync jobs writing one destination can conflict. For cron, use a shared flock lock:
*/5 * * * * /usr/bin/flock -n /tmp/sync.lock /srv/scripts/sync.sh
-n exits if it cannot obtain the lock instead of waiting. Prefer an owned protected lock path to a predictable file in a shared /tmp. All relevant entry points must honor the same lock. The lock is tied to open descriptors, not the mere existence of a file; descendants that retain descriptors can keep it held.
A timer does not start another copy of the same still-active unit. Do not background the work and exit early, and do not assume separate units are mutually exclusive. A skipped trigger is not automatically queued for later.
log() { echo "[$(date '+%F %T')] $*"; }
log "backup started"
# ... 实际工作
log "backup finished, size=$(du -h "$DEST" | cut -f1)"
Set DEST before using this illustration and distinguish successful completion from an attempted start. Record durations and outputs without logging secrets.
The source's webhook illustration is:
#!/usr/bin/env bash
set -euo pipefail
notify_fail() {
curl -fsS -X POST "https://your-webhook-url" \
-d "text=backup.sh 失败,主机 $(hostname),退出码 $?" || true
}
trap notify_fail ERR
# ... 实际工作
For trap ... ERR, capture the original exit code at the start of the handler, before hostname/curl or other commands change status; preserve it when exiting. Consider set -E for ERR-trap inheritance where required and understand its conditional exceptions. Add bounded connection/overall timeouts and safely encode notification payloads. || true prevents a notification transport failure from replacing the original failure; it is not permission to suppress the backup's failure.
Use an explicitly configured Telegram, Slack, regional collaboration service or other webhook only if your operations require it. A dead-man monitor such as healthchecks.io can alert when expected success/start signals never arrive, covering a task that did not trigger at all. Protect monitoring URLs as credentials.
#!/usr/bin/env bash
# /srv/scripts/backup-db.sh
set -euo pipefail
DEST=/srv/backups
KEEP_DAYS=14
STAMP=$(date +%F-%H%M)
mkdir -p "$DEST"
# --single-transaction 避免锁表
/usr/bin/mysqldump --single-transaction --quick \
--databases myapp \
| gzip > "$DEST/myapp-$STAMP.sql.gz"
# 校验产物不是空的
[ -s "$DEST/myapp-$STAMP.sql.gz" ] || { echo "backup is empty!"; exit 1; }
# 清理超过保留期的旧备份
find "$DEST" -name 'myapp-*.sql.gz' -mtime +$KEEP_DAYS -delete
30 3 * * * /srv/scripts/backup-db.sh >> /var/log/backup-db.log 2>&1
Provide protected credentials for the real account. --single-transaction is useful for compatible transactional tables, not a guarantee for every storage engine or concurrent schema change. [ -s ... ] only checks nonzero compressed size: an empty gzip stream can still pass it. Rely on the failed-pipeline status, verify the archive with gzip -t, inspect the dump and perform a restore drill before deleting older known-good backups. mysqldump permission failures must stop retention cleanup.
The example retains 14-day-named backups by file modification age; check find's day-rounding behavior and constrain its path/pattern. Keep an encrypted offsite copy via the file-transfer guide and test backup recovery. Local copies help with some mistakes but do not survive loss of the host/account.
# 每周日清理 30 天前的日志
0 4 * * 0 find /var/log/myapp -name '*.log' -mtime +30 -delete
This example removes matching logs older than the stated 30-day age; inspect the selected paths first and avoid deleting a file still held open by a service.
# /etc/logrotate.d/myapp
/var/log/myapp/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 www-data adm
}
logrotate supports compression and retained generations. Ensure the shown user/group exists and arrange application log reopening when necessary. Verify the system's logrotate schedule instead of adding a duplicate. Docker container logs need their own driver/rotation policy; see Docker disk usage.
systemctl list-timers | grep certbot
sudo certbot renew --dry-run
Many Certbot packages install a timer or cron job, but the name and method vary by package/snap/container. Check the installed scheduler before creating another. A renew --dry-run tests renewal against a test service and may have hook-specific behavior; monitor actual certificate expiry too. See renewal troubleshooting.
Host scheduling can run:
0 3 * * * /usr/bin/docker exec myapp-container /app/scripts/task.sh >> /var/log/task.log 2>&1
Verify the container name, task path, exit status and readiness. A one-shot job through docker compose run --rm is another option. An internal scheduler can work if lifecycle, logs and overlap are deliberately managed; it is not universally prohibited by container design.
How do I locate a missed run?
# cron 的执行记录
grep CRON /var/log/syslog | tail -20
# 或者(RHEL 系)
sudo journalctl -u crond -n 30
# systemd timer
systemctl list-timers --all
journalctl -u backup.service -n 50
Log locations and cron/crond service names vary. Correlate scheduler trigger, task account and script exit; follow scheduled-task diagnosis.
Why is the time several hours off?
timedatectl # 看当前时区
sudo timedatectl set-timezone Asia/Shanghai
The original timezone-setting command selects Asia/Shanghai; it is a regional example, not the required timezone for international readers. Choose your intended IANA zone or UTC, then recalculate business times. Check support for per-schedule timezone configuration and DST behavior. sudo systemctl restart cron may be needed for some cron implementations after host timezone changes, but review the installed daemon and running jobs first. See clock synchronization.
Can it run every 30 seconds?
# 用 sleep 错开(粗糙但能用)
* * * * * /srv/scripts/task.sh
* * * * * sleep 30; /srv/scripts/task.sh
Two cron entries offset with sleep are approximate and need shared locking. A timer can use OnUnitActiveSec=30s with AccuracySec=1s plus an initial trigger. For an interval measured after completion, consider OnUnitInactiveSec instead. A continuously running service may be better for frequent work.
What if the job runs longer than its interval? cron can start another copy unless flock prevents it. A timer does not duplicate its active service; monitor skipped runs and duration.
How do I pause it?
# cron:注释掉那一行
crontab -e
# systemd
sudo systemctl stop backup.timer # 停止(重启后会恢复)
sudo systemctl disable backup.timer # 彻底禁用
Stopping a timer does not terminate a job already running. Disable prevents automatic timer activation but does not itself stop an active timer unless combined with --now. Check both timer and service before assuming the workload is paused.
Should WordPress use a real scheduler? wp-cron is request-triggered, so low traffic can delay work. You can replace it deliberately:
// wp-config.php
define('DISABLE_WP_CRON', true);
*/5 * * * * /usr/bin/curl -fsS "https://example.com/wp-cron.php?doing_wp_cron" > /dev/null
Set the real URL, verify a successful external invocation and failure logging before disabling the request trigger. A protected WP-CLI schedule may be another option. See WordPress performance.
How do I manage several servers? Version the scripts and non-secret schedule definitions and deploy the correct file with crontab file. Configuration management can help beyond a few hosts. Keep credentials, sensitive paths and monitoring tokens out of public repositories.
Does the task need root? Use the minimum required permissions. A service account can back up its files; writing protected paths such as /var/log or managing services may require narrower delegated privileges. See VPS security.
- Test manually as the real task account;
bash -x script.shcan trace execution but may reveal secrets. - Use explicit paths and working directories.
- Review
set -euo pipefailand explicit failure checks. - Capture output instead of discarding everything with
> /dev/null 2>&1. - Rotate and limit logs.
- Use
flockor appropriate unit/lock design for overlap. - Verify timezone and clock with
timedatectl. - Inspect
systemctl list-timersand observe a real scheduled cycle. - Detect failures and missing executions.
- Restore a representative backup successfully.