在 Ubuntu(以及大多数 Linux 系统)中,trigger 和 cron 并不是同一层级的概念,它们常出现在不同场景里,因此容易混淆。下面从概念、用途、机制、常见实现几个方面来对比说明。
cron 是定时执行工具,而 trigger 通常是“事件触发执行”的机制。
cron 是 基于时间的任务调度器,按照设定的时间周期执行任务。
# 每天凌晨 2 点执行
0 2 * * * /home/user/backup.sh
/etc/crontab/etc/cron.d/crontab -e(用户级)trigger(触发器) 不是一个具体命令,而是一种**“当某事件发生时执行某动作”的机制**。
| 类型 | 示例 |
|---|---|
| 文件系统触发 | inotify、fswatch |
| 系统事件触发 | systemd path / socket |
| 数据库触发 | MySQL / PostgreSQL trigger |
| 应用层触发 | 程序内部事件 |
# path trigger
[Unit]
Description=Watch file
[Path]
PathChanged=/tmp/test.txt
[Install]
WantedBy=multi-user.target
触发服务:
[Unit]
Description=Run after file change
[Service]
ExecStart=/usr/local/bin/handle.sh
inotifywait -m /data -e create -e modify | while read path action file; do
echo "$file changed"
done
| 对比项 | cron | trigger |
|---|---|---|
| 驱动方式 | 时间 | 事件 |
| 是否周期性 | ✅ 是 | ❌ 不一定 |
| 精度 | 分钟级 | 实时 / 毫秒级 |
| 是否常驻 | ❌ 否 | ✅ 通常常驻 |
| 配置复杂度 | 简单 | 视实现而定 |
| 典型工具 | cron / crontab | systemd / inotify / db trigger |
❌ “trigger 是 Ubuntu 的一个命令”
✅ 实际上它是机制或设计模式
❌ “cron 可以做所有自动化”
✅ 不适合实时或事件驱动场景
cron = 定时闹钟,trigger = 事件感应器
如果你有具体场景(比如:文件变化执行脚本、服务启动触发任务、定时任务是否该用 cron),可以告诉我,我可以帮你选最合适的方案并给出配置示例。