Skip to main content

[SOLVED] How to Add a Timeout Step in Jenkins Pipeline? - jenkins

[SOLVED] Adding a Timeout Step in Jenkins Pipeline: A Simple Guide

In CI/CD world, managing build times is very important. It helps us keep our workflows running smoothly. This article talks about how to add a timeout step in Jenkins pipelines. This way, our jobs will not get stuck forever. We can also handle mistakes better. We will look at different ways to set timeouts in both declarative and scripted pipelines. We will also see how to deal with timeout errors and use parallel stages. By learning these methods, we can make our Jenkins pipeline more reliable and better.

In this article, we will cover these ways to add a timeout in Jenkins pipelines:

  • Part 1: Using the timeout step in Declarative Pipelines
  • Part 2: Implementing Timeout in Scripted Pipelines
  • Part 3: Setting Global Timeout for All Stages
  • Part 4: Handling Timeout Exceptions in Pipelines
  • Part 5: Using Timeout with Parallel Stages
  • Part 6: Customizing Timeout Messages

By the end of this article, we will understand how to add timeout steps in our Jenkins pipelines. This will help us have smoother and more predictable builds. If we want to learn more about related things like how to trigger another job from Jenkins or setting environment variables in Jenkins, we can check those links for more information.

Part 1 - Using the timeout Step in Declarative Pipelines

In Jenkins Declarative Pipelines, we can easily add a timeout to our stages with the timeout step. This helps us set a time for how long the stage should run. If the stage takes more time than we set, Jenkins will stop it automatically.

Here’s how we can use the timeout step in a Declarative Pipeline:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                timeout(time: 30, unit: 'MINUTES') {
                    // Your build commands here
                    sh 'make build'
                }
            }
        }
        stage('Test') {
            steps {
                timeout(time: 15, unit: 'MINUTES') {
                    // Your test commands here
                    sh 'make test'
                }
            }
        }
    }
}

In the example above:

  • We set the timeout step to 30 minutes for the ‘Build’ stage and 15 minutes for the ‘Test’ stage.
  • If the ‘Build’ stage does not finish in 30 minutes, Jenkins will stop it.

We can also change the timeout settings more by using the timeout directive at the stage level or at the pipeline level.

If we want to learn more about advanced uses, we can check how to trigger another job or how to set environment variables.

Part 2 - Implementing Timeout in Scripted Pipelines

In scripted pipelines, we can use the timeout block to set a timeout. This helps us to choose a time limit after which the pipeline will stop if it has not finished.

Here is how we can use a timeout in a scripted pipeline:

node {
    timeout(time: 5, unit: 'MINUTES') { // Set timeout for 5 minutes
        // Your build steps here
        stage('Build') {
            echo 'Building...'
            // Simulate a long-running task
            sleep(time: 300, unit: 'SECONDS') // This sleep simulates a long process
        }
    }
}

Key Points:

  • The timeout block needs two things: time and unit. We can set the time in different units like SECONDS, MINUTES, or HOURS.
  • If the steps inside the timeout take longer than the time we set, the build will fail with a timeout error.

We can check the timeout step documentation for more information on options and settings.

Also, if we want to manage many stages with different timeout rules, we can look at this guide on setting global timeout for all stages or handling timeout exceptions.

Part 3 - Setting Global Timeout for All Stages

We can set a global timeout for all stages in a Jenkins Pipeline using the options directive in a Declarative Pipeline. This will make sure that if any stage takes too long, the whole build will fail.

Example of Global Timeout in Declarative Pipeline

pipeline {
    agent any
    options {
        timeout(time: 30, unit: 'MINUTES') // Set global timeout to 30 minutes
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
                // Build steps here
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
                // Test steps here
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
                // Deployment steps here
            }
        }
    }
}

Example of Global Timeout in Scripted Pipeline

For Scripted Pipelines, we can use the timeout block at the top level. This will apply a global timeout.

node {
    timeout(time: 30, unit: 'MINUTES') { // Set global timeout to 30 minutes
        stage('Build') {
            echo 'Building...'
            // Build steps here
        }
        stage('Test') {
            echo 'Testing...'
            // Test steps here
        }
        stage('Deploy') {
            echo 'Deploying...'
            // Deployment steps here
        }
    }
}

By using a global timeout, we can manage builds that take a long time. This helps keep our Jenkins Pipeline efficient. For more about managing build environments, check out how to access build environment.

Part 4 - Handling Timeout Exceptions in Pipelines

We need to handle timeout exceptions in Jenkins pipelines. This is important, especially when we use the timeout step. We can use catchError or try-catch blocks to manage exceptions. This helps our pipeline to keep running next stages or do special tasks when a timeout happens.

Using try-catch in Declarative Pipeline

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    try {
                        timeout(time: 5, unit: 'MINUTES') {
                            // Your long-running task here
                            sh 'sleep 600'
                        }
                    } catch (err) {
                        echo "Caught: ${err}"
                        // Handle the timeout exception
                    }
                }
            }
        }
    }
}

Using catchError in Declarative Pipeline

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
                    timeout(time: 5, unit: 'MINUTES') {
                        // Your long-running task here
                        sh 'sleep 600'
                    }
                }
            }
        }
    }
}

Handling Timeouts in Scripted Pipeline

In a scripted pipeline, we can also handle timeouts by using a try-catch block:

node {
    try {
        timeout(time: 5, unit: 'MINUTES') {
            // Your long-running task here
            sh 'sleep 600'
        }
    } catch (e) {
        echo "Caught: ${e}"
        // Handle the timeout exception
    }
}

Custom Handling of Timeout Results

We can do special actions when a timeout occurs. For example, we can notify a team or log more information.

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    try {
                        timeout(time: 5, unit: 'MINUTES') {
                            // Your long-running task here
                            sh 'sleep 600'
                        }
                    } catch (err) {
                        echo "Task timed out: ${err}"
                        // Custom action on timeout
                        currentBuild.result = 'FAILURE'
                        // Maybe trigger another job
                        build job: 'NotifyTeam'
                    }
                }
            }
        }
    }
}

This way, we can manage timeout exceptions in our Jenkins pipelines. This helps our CI/CD process to stay strong and quick. For more info on handling different parts of Jenkins pipelines, we can check how to trigger another job from Jenkins or how to mark builds as unstable.

Part 5 - Using Timeout with Parallel Stages

We can use timeouts in parallel stages in a Jenkins Pipeline with the timeout step and the parallel directive. This helps us set a time limit for each parallel task. If any stage takes too long, it will stop.

Example of Timeout in Parallel Stages

pipeline {
    agent any
    stages {
        stage('Parallel Stages with Timeout') {
            parallel {
                stage('Stage 1') {
                    steps {
                        timeout(time: 5, unit: 'MINUTES') {
                            echo 'Running Stage 1...'
                            // Simulate a long-running process
                            sleep(300)
                        }
                    }
                }
                stage('Stage 2') {
                    steps {
                        timeout(time: 3, unit: 'MINUTES') {
                            echo 'Running Stage 2...'
                            // Simulate a long-running process
                            sleep(180)
                        }
                    }
                }
                stage('Stage 3') {
                    steps {
                        timeout(time: 2, unit: 'MINUTES') {
                            echo 'Running Stage 3...'
                            // Simulate a long-running process
                            sleep(120)
                        }
                    }
                }
            }
        }
    }
}

In this example, each stage runs at the same time with its own timeout. If any stage goes over its time limit, Jenkins will stop that stage.

Key Points

  • We should use the timeout directive in each stage to set the time.
  • We can set the timeout in different units like SECONDS or MINUTES.
  • If a stage times out, we can handle it nicely or let Jenkins mark it as a failed stage.

For more tips on timeouts and improving Jenkins pipelines, see how to trigger another job from Jenkins and how to authenticate Jenkins CI.

Part 6 - Customizing Timeout Messages

In Jenkins pipelines, we can change the timeout messages. This helps us understand better when a timeout happens. It is useful for finding out what went wrong during the pipeline run.

To change the timeout message in both Declarative and Scripted pipelines, we can use the timeout step with the message option.

For Declarative Pipelines

We can give a timeout message right inside the timeout block. Here is an example:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                timeout(time: 5, unit: 'MINUTES', message: 'The build has timed out due to inactivity.') {
                    // Your build steps here
                    sh 'sleep 600' // Simulated long-running step
                }
            }
        }
    }
}

For Scripted Pipelines

In Scripted pipelines, we can also use the timeout step with a message option. Here is an example:

node {
    timeout(time: 10, unit: 'MINUTES', message: 'The build has exceeded the maximum allowed time.') {
        // Your build steps here
        sh 'sleep 900' // Simulated long-running step
    }
}

By changing the timeout message, we can show clear reasons why a build fails. This helps us troubleshoot faster. For more information about Jenkins pipeline setups, we can check this article on how to trigger another job from Jenkins or learn about how to handle timeout exceptions in Jenkins.

Frequently Asked Questions

1. How do we add a timeout in a Jenkins Declarative Pipeline?

We can add a timeout in a Jenkins Declarative Pipeline by using the timeout step in the pipeline block. For example, we write timeout(time: 5, unit: 'MINUTES') { ... } to set a timeout for a stage. This will stop the stage if it runs too long. It helps our pipeline run better. For more details, check our guide on how to add a timeout step in Jenkins Pipeline.

2. Can we set a global timeout for all stages in Jenkins?

Yes, we can set a global timeout for all stages in Jenkins. We do this with the options directive in our Declarative Pipeline. For example, we can write options { timeout(time: 10, unit: 'MINUTES') }. This means if any stage takes too long, the whole pipeline will fail. For more information, look at the section on setting global timeout for all stages.

3. How do we handle timeout exceptions in Jenkins Pipelines?

To handle timeout exceptions in Jenkins Pipelines, we can use a try-catch block in a Scripted Pipeline. In a Declarative Pipeline, we can use the post section. This lets us decide what to do when a timeout happens. For example, we can send notifications or mark the build as unstable. For more examples, check the section on handling timeout exceptions in pipelines.

4. Is it possible to use timeout with parallel stages in Jenkins?

Yes! We can use the timeout step with parallel stages in Jenkins. We just need to wrap each parallel branch with a timeout block. This way, if any of the parallel stages take too long, it will fail that branch. The other branches can keep going. For more on this, see our guide on using timeout with parallel stages.

5. How can we customize timeout messages in Jenkins Pipelines?

We can customize timeout messages in Jenkins Pipelines by using the timeout step’s message parameter. For example, we can write timeout(time: 5, unit: 'MINUTES', message: 'Stage exceeded timeout!') { ... } to show our own message when the timeout happens. This helps to understand failures in our pipeline better. For more information, see our section on customizing timeout messages.

Comments