CentOS 中的 Trigger 配置指南
一 概念与适用场景
二 systemd 定时器与服务联动
[Unit]
Description=My Trigger Service
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/my_script.sh
[Unit]
Description=Timer for My Trigger Service
[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now my_service.timer
systemctl list-timers --all
journalctl -u my_service.timer -u my_service.service
三 文件事件触发脚本
sudo yum install -y inotify-tools
#!/usr/bin/env bash
WATCH_DIR="/var/www/html"
LOG="/var/log/watch_trigger.log"
inotifywait -m -e modify,create,delete,move --format '%e %w%f' "$WATCH_DIR" | while IFS= read -r event file; do
echo "$(date '+%F %T') $event $file" >> "$LOG"
# 在此添加你的业务逻辑,例如:
# systemctl reload myapp.service
done
sudo tee /etc/systemd/system/watch_trigger.service >/dev/null <<'EOF'
[Unit]
Description=Watch Trigger Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/watch_trigger.sh
Restart=always
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now watch_trigger.service
四 监控平台触发器 Zabbix Trigger 与远程命令
{Template OS Linux:system.users.num.last()}>2
sudo sed -i 's/^# EnableRemoteCommands=0/EnableRemoteCommands=1/' /usr/local/zabbix/etc/zabbix_agentd.conf
sudo systemctl restart zabbix_agentd
echo 'zabbix ALL=(ALL) NOPASSWD: /usr/local/bin/kill_user.sh' | sudo tee /etc/sudoers.d/zabbix
sudo chmod 440 /etc/sudoers.d/zabbix
sudo /usr/local/bin/kill_user.sh
五 其他常见触发器与选型建议
| 触发器类型 | 典型用途 | 关键配置/工具 | 适用场景 |
|---|---|---|---|
| systemd 定时器 | 定时/相对时间任务、与服务联动 | .timer、OnBootSec、OnUnitActiveSec、Persistent | 替代 cron、依赖管理复杂 |
| cron / anacron | 简单周期任务、非 7x24 主机保底 | crontab、/etc/crontab、anacron | 轻量周期任务 |
| inotify 文件事件 | 文件变更即时处理 | inotifywait、inotify-tools | 配置热加载、日志采集 |
| udev 硬件事件 | 设备插入/拔出响应 | /etc/udev/rules.d/*.rules | USB/磁盘热插拔 |
| Zabbix Trigger | 指标阈值告警与自动修复 | Trigger、Action、Remote command | 监控联动与自愈 |