Ubuntu 触发器使用技巧
一 核心思路与选型
二 时间触发技巧
crontab -e*/5 * * * * /path/to/script.sh >> /var/log/script.log 2>&1
myjob.service[Unit]
Description=My triggered job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/myjob.sh
myjob.timer[Unit]
Description=Run myjob every 5 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload && sudo systemctl enable --now myjob.timersystemctl list-timers三 事件触发技巧
sudo apt-get install inotify-tools#!/usr/bin/env bash
WATCH=/data/incoming
SCRIPT=/usr/local/bin/handle.sh
inotifywait -m -r -e create,modify,close_write --format '%w%f %e' "$WATCH" | \
while IFS=' ' read -r file event; do
# 简单防抖:同一文件 2 秒内只处理一次
if [[ -z "${last[$file]}" || $((SECONDS - last[$file])) -ge 2 ]]; then
"$SCRIPT" "$file" "$event" &
last["$file"]=$SECONDS
fi
done
# /etc/udev/rules.d/99-usb-backup.rules
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="1234", ATTR{idProduct}=="5678", \
RUN+="/usr/local/bin/usb-backup.sh %k"
sudo udevadm control --reload-rules && sudo udevadm trigger/etc/systemd/system/filewatcher.service[Unit]
Description=Watch a file
[Service]
Type=oneshot
ExecStart=/usr/local/bin/onfilechange.sh
/etc/systemd/system/filewatcher.path[Path]
PathModified=/data/trigger.txt
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now filewatcher.path四 实战与排错建议
>> /var/log/... 2>&1),并在 systemd 单元中使用 StandardOutput=journal 或 journalctl -u <unit> 查看。flock -n)或 systemd 的 ExecStartPre/ExecStartPost 控制并发。RUN{program} 提升权限执行。sudo systemctl stop apt-daily.timer apt-daily-upgrade.timer
sudo systemctl disable apt-daily.timer apt-daily-upgrade.timer
sudo systemctl stop apt-daily.service apt-daily-upgrade.service
sudo systemctl disable apt-daily.service apt-daily-upgrade.service