Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

October 07, 2022

Introduction

In this post we will see following:

  • How to schedule a job on cron schedule
  • How not to run job on code commit

How to Schedule Job on Cron

Jenkin pipelines are very powerful and flexible, they provide lot of options for developers. One such option is triggers.

Complete Jekninsfile:

pipeline {
    agent {
        node {
            label "MyJenkinNode"
        }
    }
    triggers {
        //every 24 hours at 12 AM
        cron('0 0 * * *')
    }
    stages {
        stage('Install requirements') {
            steps {
                    ...
                }
            } 
        }
    }
}

Above file triggers job every 24 hours, 12 AM every day.

Problem - Why We Don’t Want to Run On Code-Commit

The nature of my job is to run only on cron schedule specified. Problem will be, even if I’m changing something in any file, lets say in README or any python file, the job will be triggered.

I do not want the job to run on any code commit.

How Not to Run Job on Code Commit

The idea is to use changeset pattern with a regex pattern.

Example:

when {
    not { changeset pattern: ".*", comparator: "REGEXP" }
}

Complete file:

pipeline {
    agent {
        node {
            label "MyJenkinNode"
        }
    }
    triggers {
        //every 24 hours at 12 AM
        cron('0 0 * * *')
    }
    stages {
        stage('Install requirements') {
            when {
                not { changeset pattern: ".*", comparator: "REGEXP" }
            }
            steps {
                    ...
                }
            } 
        }
    }
}

If you want job not to run on some specific file changes, you can provide that regex pattern.


Similar Posts

Latest Posts