温馨提示×

如何设置Ubuntu Trigger自动运行

小樊
40
2025-12-18 00:15:11
栏目: 智能运维

在 Ubuntu 中,“Trigger”通常指基于时间或事件的自动化触发机制。常见做法包括:按时间调度的 cronsystemd 定时器,按系统事件的 systemd 服务,按文件变化的 inotify,以及登录时自动启动的 桌面自启动。下面按场景给出可直接使用的配置方法与排错要点。

常用触发方式与选择建议

  • 定时触发:用 cron 快速设置周期任务;需要更复杂依赖、日志与并发控制时,用 systemd 定时器
  • 事件触发:系统启动/关机/网络就绪等用 systemd 服务;文件或目录被创建/修改时用 inotify
  • 登录触发:带桌面环境的 Ubuntu 可将应用加入 ~/.config/autostart/ 实现用户登录即启动。

操作步骤

  • 定时触发(cron)

    1. 编辑当前用户的计划任务:运行 crontab -e
    2. 添加规则(示例:每天 02:00 执行脚本):
      0 2 * * * /usr/bin/python3 /home/user/backup.py
      提示:脚本建议使用绝对路径,并在脚本首行声明解释器(如 #!/usr/bin/env python3)。
    3. 常用管理:查看任务 crontab -l;查看/启动服务 sudo service cron status/start
    4. 日志排查:启用 /var/log/cron.log(编辑 /etc/rsyslog.d/50-default.conf,取消注释 cron. /var/log/cron.log*,重启 rsyslog),再用 tail -f /var/log/cron.log 观察执行情况。
  • 定时触发(systemd 定时器,替代/增强 cron)

    1. 创建服务单元 /etc/systemd/system/my_script.service
      [Unit]
      Description=My script
      [Service]
      Type=oneshot
      ExecStart=/usr/bin/python3 /home/user/backup.py
      User=youruser
    2. 创建定时器 /etc/systemd/system/my_script.timer
      [Unit]
      Description=Run my_script hourly
      [Timer]
      OnBootSec=1min
      OnUnitActiveSec=1h
      Unit=my_script.service
      [Install]
      WantedBy=timers.target
    3. 启用并启动:
      sudo systemctl daemon-reload
      sudo systemctl enable --now my_script.timer
    4. 检查:
      systemctl list-timers
      journalctl -u my_script.service -b
  • 事件触发(systemd 服务)

    1. 创建服务 /etc/systemd/system/my_trigger.service
      [Unit]
      Description=Run on boot or network ready
      After=network.target
      [Service]
      Type=simple
      ExecStart=/home/user/startup.sh
      Restart=on-failure
    2. 启用:
      sudo systemctl daemon-reload
      sudo systemctl enable --now my_trigger.service
    3. 说明:After= 可设为 network.target、multi-user.target 等,以匹配你的依赖事件。
  • 文件变化触发(inotify)

    1. 安装工具:sudo apt-get install inotify-tools
    2. 监控并在变化时执行脚本:
      inotifywait -m -e modify,create,delete /path/to/dir | while read path action file; do
      /home/user/handle.sh “$path$file” “$action”
      done
    3. 后台常驻:nohup ./watch.sh &;建议写入 systemd 服务以便开机自启与日志管理。
  • 登录时自动启动(桌面环境)

    1. 创建桌面文件 ~/.config/autostart/myapp.desktop
      [Desktop Entry]
      Type=Application
      Name=MyApp
      Exec=/usr/bin/python3 /home/user/app.py
      Hidden=false
    2. 重新登录即可自动启动。

实用建议与排错

  • 使用绝对路径调用脚本与解释器;在脚本中显式设置环境变量(如 PATH、HOME),因为 cron 与系统服务的环境与登录会话不同。
  • 权限与用户:需要系统级权限请使用 sudo 创建服务;服务单元中通过 User= 指定运行身份。
  • 日志与状态:
    • cron:启用 /var/log/cron.log 并用 tail -f 实时查看。
    • systemd:用 systemctl status my_trigger.servicejournalctl -u my_trigger.service -b 定位问题。
    • 定时器:用 systemctl list-timers 确认下一次触发时间。
  • 避免重复运行:inotify 循环内注意加锁或状态判断;systemd 服务可用 Restart=on-failure 并配合 Type=oneshot/simple 合理选择。

0