Daniel Paczuski Bak
Daniel Paczuski Bak

Reputation: 4088

Jenkinsfile - timed (cron) trigger only if changes detected

I have a Jenkinsfile.

I would like to do a nightly build (at let's say midnight), but only if changes were detected since the previous build.

How would I accomplish this?

Upvotes: 2

Views: 1203

Answers (1)

Adam
Adam

Reputation: 807

You can use:

pipeline {
    agent any
    triggers {
        pollSCM('H */4 * * 1-5')
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

As per the Jenkins documentation, pollSCM does the following:

Accepts a cron-style string to define a regular interval at which Jenkins should check for new source changes. If new changes exist, the Pipeline will be re-triggered.

There's a more complicated way to accomplish same behaviour (just an alternative to pollSCM), that is putting a normal cron:

triggers {
    cron('H */4 * * 1-5')
}

And then checking for changes with the environment variables:

stage('Example') {
    when {
       expression {
           !env.currentBuild.changeSets.isEmpty()
       }
    }
    steps {
        echo 'Hello World'
    }
}

Also per the docs, env.currentBuild.changeSets:

This is a list of changesets coming from distinct SCM checkouts; each has a kind and is a list of commits; each commit has a commitId, timestamp, msg, author, and affectedFiles each of which has an editType and path; the value will not generally be Serializable so you may only access it inside a method marked @NonCPS

Reference:

Upvotes: 4

Related Questions