Setting a "Timeout" To Cancel Builds
There are situations where you may wish to cancel your build after a set amount of time, such as if you know you have long running tests and don't want to allow them to eat up credits.
You can add a background step that will accomplish this, think of it as starting a stop watch and when the set amount of time has elapsed, it will cancel the build.
First you'll need to generate a personal API token and store that as a variable (CIRCLE_TOKEN) either in the project settings or a context. Once that is done, you can add this run command to your job that you want to have a timer on:
- run:
name: Cancel build after set time
background: true
command: |
sleep 1000
echo "Canceling workflow as too much time has elapsed"
curl -X POST --header "Content-Type: application/json" "https://circleci.com/api/v2/workflow/${CIRCLE_WORKFLOW_ID}/cancel?circle-token=${CIRCLE_TOKEN}"
The only adjustment in the above step you'll need to make is for how long you want to wait before the API call executes, change that by adjusting the sleep 1000 to the value of how long you want to wait.
If you only want to cancel a specific job, you can make use of:
circleci-agent step halt
This will only cancel the job it is running in, but does not require the use of an API key, so may be simpler in some circumstances.
Comments
Article is closed for comments.