You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置systemd timers让三个任务按指定时间依次顺序执行?

用Systemd复刻Cron每日顺序执行任务的方案

你当前通过Cron每日按文件名顺序执行三个脚本,要迁移到Systemd且保持顺序执行,有两种实用方案:

方案1:整合为单个Oneshot服务(最贴近原Cron逻辑)

这种方式把三个脚本打包成一个任务集合,完全复刻Cron的顺序执行逻辑:

  1. 创建整合执行脚本
    新建/usr/local/bin/daily-tasks.sh(路径可自定义),内容如下:

    #!/bin/bash
    # 按顺序执行原脚本,前一个失败则终止后续(如需忽略失败去掉&&)
    /etc/cron.daily/1task-A.sh && \
    /etc/cron.daily/2task-B.sh && \
    /etc/cron.daily/3task-C.sh
    

    给脚本添加执行权限:

    chmod +x /usr/local/bin/daily-tasks.sh
    
  2. 创建Systemd服务文件
    新建/etc/systemd/system/daily-tasks.service:

    [Unit]
    Description=每日顺序执行任务集合
    
    [Service]
    Type=oneshot
    ExecStart=/usr/local/bin/daily-tasks.sh
    # 可选:若需要输出日志到journald之外的文件,可添加StandardOutput=append:/var/log/daily-tasks.log
    
  3. 创建Timer定时器文件
    新建/etc/systemd/system/daily-tasks.timer:

    [Unit]
    Description=每日任务集合定时器
    
    [Timer]
    OnCalendar=daily  # 每日执行,默认0点0分;可自定义如"*-*-* 02:30:00"
    Persistent=true   # 系统关机错过执行时间时,开机后自动补跑
    
    [Install]
    WantedBy=timers.target
    
  4. 启用并启动定时器

    systemctl daemon-reload
    systemctl enable --now daily-tasks.timer
    

方案2:利用Systemd服务依赖实现连锁执行

如果需要保留三个任务的独立性(比如可单独手动触发某一个),可通过服务依赖让它们按顺序触发:

  1. 创建三个独立的服务文件

    • task-A.service(/etc/systemd/system/):
      [Unit]
      Description=任务A
      
      [Service]
      Type=oneshot
      ExecStart=/etc/cron.daily/1task-A.sh
      
      [Install]
      WantedBy=multi-user.target
      Also=task-B.service  # 任务A执行完成后自动启动任务B
      
    • task-B.service(/etc/systemd/system/):
      [Unit]
      Description=任务B
      Requires=task-A.service  # 任务A必须成功执行,否则任务B不启动(换成Wants则允许A失败)
      After=task-A.service     # 确保任务A执行完成后再启动任务B
      
      [Service]
      Type=oneshot
      ExecStart=/etc/cron.daily/2task-B.sh
      
      [Install]
      WantedBy=multi-user.target
      Also=task-C.service  # 任务B执行完成后自动启动任务C
      
    • task-C.service(/etc/systemd/system/):
      [Unit]
      Description=任务C
      Requires=task-B.service
      After=task-B.service
      
      [Service]
      Type=oneshot
      ExecStart=/etc/cron.daily/3task-C.sh
      
      [Install]
      WantedBy=multi-user.target
      
  2. 创建触发任务A的Timer文件
    新建/etc/systemd/system/task-A.timer:

    [Unit]
    Description=任务A每日定时器
    
    [Timer]
    OnCalendar=daily
    Persistent=true
    
    [Install]
    WantedBy=timers.target
    
  3. 启用并启动定时器

    systemctl daemon-reload
    systemctl enable --now task-A.timer
    

方案对比

  • 方案1:配置简单,日志集中,完全匹配原Cron的执行逻辑,适合不需要单独调度单个任务的场景。
  • 方案2:任务独立,可单独启动任意任务,适合后续可能需要调整单个任务调度规则的场景。

内容的提问来源于stack exchange,提问作者Graham Leggett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:12:36