CentOS 中的 Trigger 管理指南
概念澄清
常用实现与对应管理命令
| 场景 | 核心机制 | 关键文件/命令 | 常用管理动作 |
|---|---|---|---|
| 定时或事件驱动任务 | systemd timer | 单元:.timer/.service;命令:systemctl enable/start/stop/status my.timer,systemctl list-timers,journalctl -u my.timer | 创建 .timer 定义 OnBootSec/OnCalendar/OnUnitActiveSec;启用并启动定时器,查看状态与日志 |
| 简单周期任务 | cron | 系统级:/etc/crontab;用户级:crontab -e | 编辑条目(分 时 日 月 周 命令);适合固定频率任务 |
| 文件变更触发 | inotifywait | 工具:inotify-tools(安装:yum install inotify-tools);脚本循环监听 | 监听目录/文件事件并调用业务脚本,适合“文件落地即处理” |
| 数据库行级触发 | MySQL 触发器 | 语法:CREATE TRIGGER … BEFORE/AFTER INSERT/UPDATE/DELETE | 在表上定义自动逻辑(如字段默认、审计) |
| 包操作触发 | yum/dnf 触发器/插件 | 命令:yum/dnf install/update/remove;插件:yum-plugin-trigger | 安装/更新/删除包时自动执行脚本或动作(需谨慎配置) |
| 以上要点与命令示例可参考 systemd timer、cron、inotify 与 MySQL 触发器、yum/dnf 触发器实践。 |
快速上手示例
[Unit]
Description=Hello Trigger Service
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/hello.sh
[Unit]
Description=Run hello.service every 5 minutes
Requires=hello.service
[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now hello.timer
systemctl list-timers --all
journalctl -u hello.timer -u hello.service
#!/usr/bin/env bash
inotifywait -m /data/incoming -e create,modify,close_write |
while read path action file; do
echo "$(date) $action $file" >> /var/log/watch.log
/usr/local/bin/handle.sh "/data/incoming/$file"
done
实践建议与排错