CentOS 触发器定制化方法
一、方案总览与选型
二、systemd Timer 时间触发
[Unit]
Description=Daily Backup
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
[Install]
WantedBy=multi-user.target
[Unit]
Description=Run backup daily at 02:00
Requires=backup.service
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
systemctl list-timers --all
journalctl -u backup.service -b
三、systemd path 与 inotifywait 文件事件触发
[Unit]
Description=Handle uploaded file
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/process_upload.sh %f
[Unit]
Description=Watch /data/upload for new files
[Path]
PathModified=/data/upload
DirectoryNotEmpty=/data/upload
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now handle_upload.path
journalctl -u handle_upload.service -f
sudo yum install -y inotify-tools
#!/usr/bin/env bash
WATCH_DIR="/data/upload"
SCRIPT="/usr/local/bin/process_upload.sh"
LOCK="/tmp/handle_upload.lock"
INOTIFYWAIT="/usr/bin/inotifywait"
mkdir -p "$WATCH_DIR"
"$INOTIFYWAIT" -m -r -e create,modify,delete --format '%w%f %e' "$WATCH_DIR" | while IFS=' ' read -r file event; do
# 简单去重:同一文件在短时间多次变更只处理一次
if ( set -C; flock -n 9; ) 9>"$LOCK"; then
sleep 5
if [[ -f "$file" ]]; then
"$SCRIPT" "$file" "$event"
fi
rm -f "$LOCK"
fi
done
[Unit]
Description=File watcher for upload
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/file_watcher.sh
Restart=on-failure
[Install]
WantedBy=multi-user.target
四、cron 与数据库触发器
# 每天 02:00 执行
0 2 * * * /usr/local/bin/backup.sh
# 每 5 分钟执行
*/5 * * * * /usr/local/bin/healthcheck.sh
查看与管理:crontab -e/-l;日志:/var/log/cron。DELIMITER //
CREATE TRIGGER before_insert_user
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
IF NEW.status IS NULL THEN
SET NEW.status = 'active';
END IF;
END //
DELIMITER ;
要点:触发器属于数据库对象,与操作系统事件无关,适合在INSERT/UPDATE/DELETE 前后执行业务规则。五、实践建议与排错清单