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

如何利用GitHub Actions Concurrency实现任务失败时取消其余任务?

解决方案

要实现Lint或JS测试失败时立即取消剩余任务,需要明确GitHub Actions的concurrency特性仅针对不同Workflow运行实例,无法直接用于同一实例内的Job间取消。针对你的需求,有两种可行方案:

方案一:依赖前置检查(简单直接)

通过needs字段让后端测试Job仅在Lint和JS测试都成功后才启动,从根源避免无效运行:

name: my-app
on:
  push:
    branches-ignore:
      - my_ignore_branch
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
env:
  SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
jobs:
  application-backend-lint:
    runs-on: ubuntu-22.04
    steps:
      # 你的Lint执行步骤
      - name: Run backend lint
        run: ...

  application-js-tests:
    runs-on: ubuntu-22.04
    steps:
      # 你的JS测试执行步骤
      - name: Run JS tests
        run: ...

  application-backend-test:
    runs-on: ubuntu-22.04
    # 仅当前置Job全部成功时才启动
    needs: [application-backend-lint, application-js-tests]
    steps:
      # 你的后端测试执行步骤
      - name: Run backend tests
        run: ...

优缺点:配置简单无额外依赖,但总耗时会增加(后端测试需等待Lint完成)。

方案二:并行启动+失败时主动取消(节省时间)

允许三个Job并行启动,当Lint或JS测试失败时,通过GitHub API主动取消正在运行的后端测试Job:

步骤1:添加API权限

在Workflow顶层添加权限配置,允许操作Actions资源:

name: my-app
on:
  push:
    branches-ignore:
      - my_ignore_branch
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
env:
  SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
# 添加权限,允许取消Job
permissions:
  actions: write
jobs:
  # 后续Job配置...

步骤2:在Lint/JS测试Job中添加取消逻辑

在Lint和JS测试的失败分支中,调用GitHub CLI取消后端测试Job:

application-backend-lint:
  runs-on: ubuntu-22.04
  steps:
    - name: Checkout code
      uses: actions/checkout@v4
    # 你的Lint执行步骤
    - name: Run backend lint
      run: ...
    # 失败时取消后端测试
    - name: Cancel backend test if lint fails
      if: failure()
      run: |
        gh run cancel ${{ github.run_id }} --job application-backend-test
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

application-js-tests:
  runs-on: ubuntu-22.04
  steps:
    - name: Checkout code
      uses: actions/checkout@v4
    # 你的JS测试执行步骤
    - name: Run JS tests
      run: ...
    # 失败时取消后端测试
    - name: Cancel backend test if JS tests fail
      if: failure()
      run: |
        gh run cancel ${{ github.run_id }} --job application-backend-test
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

application-backend-test:
  runs-on: ubuntu-22.04
  steps:
    - name: Checkout code
      uses: actions/checkout@v4
    # 你的后端测试执行步骤
    - name: Run backend tests
      run: ...

说明:Ubuntu 22.04 Runner默认预装GitHub CLI,无需额外安装;GITHUB_TOKEN会自动注入,具备当前Workflow的操作权限。

优缺点:并行启动可节省总耗时(后端测试无需等待Lint完成),但需额外配置权限和取消步骤。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:25:48