以下是Linux Trigger新手必看的配置指南:
Trigger是一种在特定事件(如系统启动、文件修改、定时任务等)发生时自动执行脚本或命令的机制,常用于自动化任务调度。
Systemd触发器(推荐)
/etc/systemd/system/my_service.service
),定义要执行的脚本:[Unit]
Description=My Custom Service
[Service]
Type=oneshot
ExecStart=/path/to/your/script.sh
/etc/systemd/system/my_trigger.trigger
),设置触发条件(如OnBootSec=5min
表示系统启动5分钟后触发):[Trigger]
OnBootSec=5min
Unit=my_service.service
sudo systemctl daemon-reload
sudo systemctl enable --now my_trigger.trigger
Cron定时触发器
crontab -e
0 2 * * * /path/to/your/script.sh
Ubuntu Trigger工具
sudo apt update && sudo apt install ubuntu-trigger
ubuntu-trigger create --name "DailyTask" --command "/path/to/script.sh" --every "0 10 * * *"
ubuntu-trigger enable "DailyTask"
文件监控触发器(inotify)
sudo apt install inotify-tools
monitor.sh
):#!/bin/bash
inotifywait -m /path/to/monitor -e create |
while read path action file; do
/path/to/your/script.sh "$file"
done
chmod +x monitor.sh
./monitor.sh
chmod +x script.sh
)。echo "$(date) - Task executed" >> /var/log/trigger.log
),方便排查问题。systemctl
命令管理触发器状态(如systemctl status my_trigger.trigger
)。cp /etc/systemd/system/my_service.service /etc/systemd/system/my_service.service.bak
)。man systemd.trigger
man inotifywait