How to Use Triggers in Jenkins Pipeline for Automated Builds
In Jenkins Pipeline, you use the
triggers block inside your pipeline to define events that start your build automatically, such as SCM changes or scheduled cron jobs. Common triggers include pollSCM for source code changes and cron for timed builds.Syntax
The triggers block defines when the pipeline should start automatically. It is placed inside the pipeline block or set as job properties. Common triggers include:
pollSCM('cron-syntax'): Checks source code changes at intervals.cron('cron-syntax'): Runs the pipeline on a schedule.upstream(triggeredJob): Starts when another job finishes.
Example syntax inside a declarative pipeline:
groovy
pipeline {
triggers {
pollSCM('H/15 * * * *')
cron('H 4 * * 1-5')
}
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
}Example
This example shows a Jenkins declarative pipeline that triggers a build every 15 minutes if there are SCM changes and also runs at 4 AM on weekdays regardless of changes.
groovy
pipeline {
agent any
triggers {
pollSCM('H/15 * * * *')
cron('H 4 * * 1-5')
}
stages {
stage('Build') {
steps {
echo 'Starting build triggered by SCM change or schedule.'
}
}
}
}Output
[Pipeline] Start of Pipeline
[Pipeline] echo
Starting build triggered by SCM change or schedule.
[Pipeline] End of Pipeline
Common Pitfalls
Common mistakes when using triggers in Jenkins pipelines include:
- Using
pollSCMwithout SCM configured, so no builds trigger. - Incorrect cron syntax causing triggers to never run.
- Placing
triggersoutside thepipelineblock in declarative pipelines. - Expecting
pollSCMto trigger immediately after a commit; it only checks on schedule.
Example of wrong and right placement:
groovy
// Wrong: triggers outside pipeline block triggers { pollSCM('H/15 * * * *') } pipeline { agent any stages { stage('Build') { steps { echo 'Build' } } } } // Right: triggers inside pipeline block pipeline { agent any triggers { pollSCM('H/15 * * * *') } stages { stage('Build') { steps { echo 'Build' } } } }
Quick Reference
Here is a quick summary of common Jenkins pipeline triggers:
| Trigger | Description | Example |
|---|---|---|
| pollSCM | Checks source code changes on schedule | pollSCM('H/15 * * * *') |
| cron | Runs pipeline on a fixed schedule | cron('H 4 * * 1-5') |
| upstream | Triggers when another job completes | upstream('OtherJob') |
| githubPush | Triggers on GitHub push events (requires plugin) | githubPush() |
Key Takeaways
Use the triggers block inside the pipeline to automate build starts.
pollSCM triggers builds on source code changes at scheduled intervals.
cron triggers builds on a fixed time schedule using cron syntax.
Always place triggers inside the pipeline block in declarative pipelines.
Check cron syntax carefully to avoid missed or unexpected triggers.