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

如何仅在GitHub Actions定时任务失败时触发Slack通知?

GitHub Actions定时任务触发问题+仅定时失败发Slack通知配置优化

问题描述

需要实现仅当cron定时调度触发的作业失败时发送Slack通知,测试时设置了强制失败步骤,但定时任务始终没触发(脚本在main分支,理论上符合触发条件)。当前配置如下:

on: 
  push:
  schedule:
    - cron: '*/5 * * * *'

jobs:
  test-fail:
    runs-on: ubuntu-latest
    steps:
    - name: force fail
      run: exit 1

  test-skip:
    if: github.ref == 'refs/heads/master'
    runs-on: ubuntu-latest
    steps:
    - name: force fail
      run: exit 1

  slackNotification:
    if: ${{ github.event_name == 'schedule' && (needs.test-fail.result == 'failure' || needs.test-skip.result == 'failure') }}
    needs: [test-fail, test-skip]...

用always()的话通知能正常工作,但push触发CI时也会发通知,不符合需求。


配置分析与修正

1. 定时任务不触发的核心原因

  • GitHub调度延迟:高频的*/5 * * * *调度不会严格每5分钟执行,GitHub的定时任务调度存在随机性延迟,有时会延迟几十分钟甚至更久,建议先测试低频率调度(比如0 12 * * *)验证是否触发。
  • 分支判断不匹配:test-skip作业的条件是github.ref == 'refs/heads/master',但你的代码在main分支,定时任务触发时github.ref是仓库默认分支(即main),所以这个作业会被标记为skipped,不会执行。

2. Slack通知条件的优化

原配置的条件逻辑接近正确,但有两处细节需要调整:

  • 去掉多余的${{ }}嵌套(YAML条件表达式支持直接写逻辑)
  • 修正分支判断,确保test-skip在main分支的定时任务中能正常执行(如果需要保留这个作业的话)

修正后的完整配置:

on: 
  push:
  schedule:
    - cron: '*/5 * * * *'

jobs:
  test-fail:
    runs-on: ubuntu-latest
    steps:
    - name: force fail
      run: exit 1

  test-skip:
    # 修正为匹配main分支
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
    - name: force fail
      run: exit 1

  slackNotification:
    # 仅在schedule事件触发,且至少一个依赖作业失败时执行
    if: github.event_name == 'schedule' && (needs.test-fail.result == 'failure' || needs.test-skip.result == 'failure')
    needs: [test-fail, test-skip]
    runs-on: ubuntu-latest
    steps:
    - name: Send Slack failure notification
      uses: slackapi/slack-github-action@v1.24.0
      with:
        slack-message: "定时调度的作业执行失败,请检查!"
      env:
        SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

额外排查点

  • 若仓库是私有仓库:超过60天无活动的话,定时任务会被暂停,需要手动触发一次工作流恢复。
  • 查看工作流历史:在仓库Actions页面,切换到对应工作流,滚动到下方查看是否有schedule触发的记录(push触发的记录会排在前面)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:06:27