Scripted pipeline: Is a job triggered by pipelineTrigger?

889 views
Skip to first unread message

Markus "Shorty" Uckelmann

unread,
Aug 14, 2018, 5:07:43 AM8/14/18
to Jenkins Users
Hi all,

I use the following code to trigger a job on a daily basis:

properties([[$class: 'BuildDiscarderProperty',
strategy: [$class: 'LogRotator', numToKeepStr: '10']],
pipelineTriggers([cron( env.BRANCH_NAME == 'master' ?
'@hourly' : '' )]),
])

Now I'd like to know, if the job was triggered by the cron trigger. Does
anybody know how this can be done?

I already tried this peace:

if (manager.logContains("Started by timer")){
echo "This build was triggered by a timer."
}

But it gave me the error: groovy.lang.MissingPropertyException: No such
property: manager for class: groovy.lang.Binding


Cheers, Shorty

Stuart Rowe

unread,
Aug 14, 2018, 1:06:00 PM8/14/18
to Jenkins Users
You can check the Run instance for a TimerTriggerCause. See: https://javadoc.jenkins-ci.org/hudson/model/Run.html#getCause-java.lang.Class-

Since this is in pipeline, you would need to access the Run within a @NonCPS method. Also, you would need to whitelist the RunWrapper#getRawBuild method.

import hudson.triggers.TimerTrigger.TimerTriggerCause
import org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper

@NonCPS
boolean wasTriggeredByTimer(RunWrapper runWrapper) {
  return null != runWrapper.getRawBuild().getCause(TimerTriggerCause.class)
}

// used within a pipeline script
if (wasTriggeredByTimer(currentBuild)) {
    echo("This build was triggered by a timer.")
}


Hope that helps!
Reply all
Reply to author
Forward
0 new messages