0
0
JenkinsHow-ToBeginner · 3 min read

How to Use Timeout in Jenkins Pipeline

In Jenkins pipeline, use the timeout step to limit the maximum time a block of code can run. Wrap the code inside timeout(time: X, unit: 'MINUTES') to stop the build if it exceeds the specified time.
📐

Syntax

The timeout step wraps a block of pipeline code and stops it if it runs longer than the specified time.

  • time: Number of time units to wait.
  • unit: Time unit like 'SECONDS', 'MINUTES', or 'HOURS'. Default is 'MINUTES'.
  • The code block inside timeout is the part that will be limited.
groovy
timeout(time: 10, unit: 'MINUTES') {
    // code to run with timeout
}
💻

Example

This example shows a Jenkins pipeline that waits for 15 minutes but will abort if it takes longer than 5 minutes.

groovy
pipeline {
    agent any
    stages {
        stage('Timeout Example') {
            steps {
                timeout(time: 5, unit: 'MINUTES') {
                    echo 'Starting long task...'
                    sleep(time: 15, unit: 'MINUTES')
                    echo 'This will not be reached if timeout triggers.'
                }
            }
        }
    }
}
Output
[Pipeline] timeout Timeout set to 5 minutes [Pipeline] { [Pipeline] echo Starting long task... [Pipeline] sleep Sleeping for 15 min [Pipeline] // timeout Timeout has been exceeded [Pipeline] } [Pipeline] // timeout ERROR: script returned exit code 143 Finished: FAILURE
⚠️

Common Pitfalls

Common mistakes when using timeout include:

  • Not wrapping the correct block of code, so timeout does not apply where expected.
  • Using too short a timeout causing premature aborts.
  • Forgetting to specify the unit, which defaults to minutes and may cause confusion.
  • Not handling the timeout exception if you want to perform cleanup or retries.
groovy
/* Wrong: timeout outside the stage, does not limit the intended code */
pipeline {
    agent any
    stages {
        timeout(time: 1, unit: 'MINUTES')
        stage('Build') {
            steps {
                sleep(time: 2, unit: 'MINUTES')
            }
        }
    }
}

/* Right: timeout wraps the steps block */
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                timeout(time: 1, unit: 'MINUTES') {
                    sleep(time: 2, unit: 'MINUTES')
                }
            }
        }
    }
}
📊

Quick Reference

Summary tips for using timeout in Jenkins pipeline:

  • Use timeout(time: X, unit: 'MINUTES') to limit execution time.
  • Wrap only the code that needs the timeout.
  • Handle timeout exceptions if cleanup is needed.
  • Units can be SECONDS, MINUTES, or HOURS.

Key Takeaways

Use the timeout step to limit how long a pipeline block runs.
Always specify time and unit to avoid confusion.
Wrap only the code you want to limit inside the timeout block.
Be aware that timeout aborts the build and may throw an exception.
Handle timeout exceptions if you need to clean up or retry.