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

如何实现GitHub Actions工作流结束后3小时触发下一次执行?

解决GitHub Actions脚本结束后间隔3小时触发的问题

要实现脚本执行结束后间隔3小时再启动下一次(而非固定时间点触发),不能用常规Cron(固定时间)或Sleep(浪费Runner资源),可以通过「记录上次执行结束时间+定时检查」的方式实现,具体如下:

核心方案

通过仓库内的文件记录脚本上次执行结束的时间,配合低频率Cron定时检查,当当前时间与记录时间的差值≥3小时时,才执行脚本并更新记录时间。这种方式几乎不浪费免费额度,因为大部分检查步骤会快速退出。

具体实现

1. 工作流代码示例

创建一个同时支持Cron触发和手动触发的工作流(保存为.github/workflows/scheduled-run.yml):

name: Scheduled Script Execution
on:
  schedule:
    - cron: '*/5 * * * *'  # 每5分钟检查一次,可按需调整频率
  workflow_dispatch:  # 支持手动触发测试

jobs:
  execute-script:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4

      - name: Verify time interval
        id: check_interval
        run: |
          # 首次运行无记录文件,直接允许执行
          if [ ! -f last_run_end.txt ]; then
            echo "can_run=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          
          # 计算时间差(单位:秒)
          LAST_END=$(cat last_run_end.txt)
          CURRENT_SEC=$(date -u +'%s')
          LAST_SEC=$(date -d "$LAST_END" +'%s')
          DIFF=$((CURRENT_SEC - LAST_SEC))
          
          # 3小时=10800秒,满足则标记可执行
          [ $DIFF -ge 10800 ] && echo "can_run=true" >> "$GITHUB_OUTPUT" || echo "can_run=false" >> "$GITHUB_OUTPUT"

      - name: Run Python script
        if: steps.check_interval.outputs.can_run == 'true'
        run: |
          # 替换为你的Python脚本执行命令
          python your_script.py

      - name: Update end time record
        if: steps.check_interval.outputs.can_run == 'true'
        run: |
          # 写入UTC时间,避免时区问题
          date -u +'%Y-%m-%dT%H:%M:%SZ' > last_run_end.txt

      - name: Commit and push record
        if: steps.check_interval.outputs.can_run == 'true'
        uses: EndBug/add-and-commit@v9
        with:
          message: 'Update last script end time'
          add: 'last_run_end.txt'

2. 关键细节说明

  • 时间记录格式:使用UTC时间的ISO 8601格式,避免不同时区导致的计算误差。
  • Cron频率:设置为每5分钟检查一次足够满足需求,频率越低消耗的免费额度越少;如果对触发及时性要求不高,甚至可以设为每15分钟一次。
  • 权限配置:确保仓库的GitHub Actions权限允许推送代码,可在仓库Settings > Actions > General中开启「Allow GitHub Actions to create and approve pull requests」,add-and-commit action默认使用GITHUB_TOKEN即可完成推送。

替代思路(进阶)

如果不想用仓库文件记录时间,也可以通过GitHub Issues的标签/备注来存储上次结束时间,或者使用GitHub API创建下一次的延迟触发事件,但文件记录的方式最简洁易实现,无需额外API权限。

内容的提问来源于stack exchange,提问作者Juan Pablo Benitez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:06:22