Cancel obsolete Jenkins queued builds

As the Jenkins builds take longer to run, we found that multiple builds are ending up on the build queue. As we are only interested in the very latest build, the older build requests are effectively obsolete. By using the Groovy plugin, we were able to write a script to cancel the old build requests. We added an Execute system Groovy script build step with the following command:

println("Analysing Jenkins queue...");
jobName = Thread.currentThread().executable.toString().split()[0];
for (item in hudson.model.Hudson.instance.getQueue().getItems()) {
  if (jobName.equals(item.task.getName())) {
    println("Aborting current build due to a more recent build request.");
    hudson.model.Executor.currentExecutor().interrupt();
    break;
  }
}

The script basically searches the build queue for any build requests that have the same name as itself. If any are found, the script terminates the current build. The current build status will then show as aborted.

Tags:

1 comment

  1. I tried this, but couldn’t get it to work. Then i found this bug: https://issues.jenkins-ci.org/browse/JENKINS-15748. It seems groovy can’t abort builds. A workaround is to throw an InterruptedException instead:

    if (jobName.equals(item.task.getName())) {
    println(“Aborting current build due to a more recent build request.”);
    throw new InterruptedException();
    }

Leave a Reply

Your email address will not be published. Required fields are marked *