Ubuntu 定时器与其他工具的协同使用
一 方案总览与选择
二 与常用工具的配合范式
与网络请求工具(wget/curl)
与桌面通知 notify-send
与日志与监控工具(journalctl、systemctl)
与文件系统事件(inotifywait)
与一次性任务(at)
与网络与安全工具(ufw/iptables)
三 两个可复用的最小示例
示例一 systemd Timer + wget 每小时拉取文件
[Unit]
Description=定时下载服务
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/wget -O /data/latest.zip https://example.com/file.zip
User=ubuntu
Group=ubuntu
[Unit]
Description=每小时执行一次下载
Requires=dl.service
[Timer]
OnBootSec=1min
OnUnitActiveSec=1h
Unit=dl.service
[Install]
WantedBy=timers.target
示例二 cron + inotifywait 实现“定时+变更”双触发备份
#!/usr/bin/env bash
set -Eeuo pipefail
WATCH=/data/in
SCRIPT=/usr/local/bin/backup.sh
inotifywait -m "$WATCH" -e create,modify,delete |
while read path action file; do
"$SCRIPT" "$path$file"
done
四 实践要点与排错清单