Polling SCM vs Webhooks in Jenkins
Introduction
In Jenkins, Continuous Integration (CI) involves integrating code changes from multiple contributors into a shared repository frequently. Two common methods of triggering builds based on changes in source control are Polling SCM and Webhooks.
Polling SCM
Polling SCM is a method where Jenkins periodically checks the source code repository for changes. If a change is detected, Jenkins triggers a build.
How Polling SCM Works
- Jenkins is configured with a schedule (e.g., every 5 minutes).
- Jenkins checks the SCM for any changes.
- If changes are found, Jenkins triggers a build.
- The build results are reported back to the user interface.
Configuration Example
pipeline {
agent any
triggers {
pollSCM('H/5 * * * *') // Poll every 5 minutes
}
stages {
stage('Build') {
steps {
echo 'Building..'
}
}
}
}
Webhooks
Webhooks are a way for an SCM to notify Jenkins immediately when changes are made. Instead of Jenkins polling for changes, the SCM sends a POST request to Jenkins when a change occurs.
How Webhooks Work
- A change is made in the SCM repository.
- The SCM sends an HTTP POST request to a specified Jenkins endpoint.
- Jenkins receives the request and triggers a build immediately.
- The build results are reported back to the user interface.
Configuration Example
pipeline {
agent any
triggers {
gitHubPush() // Triggers on GitHub webhook
}
stages {
stage('Build') {
steps {
echo 'Building..'
}
}
}
}
Comparison
Feature | Polling SCM | Webhooks |
---|---|---|
Trigger Method | Periodic checking | Immediate notification |
Resource Usage | Higher (due to regular checks) | Lower (only on changes) |
Latency | Depends on polling interval | Real-time |
Configuration Complexity | Simple | Requires webhook setup |
Best Practices
- Use webhooks when possible for immediate build triggers.
- Limit polling frequency to reduce resource usage if you must poll.
- Monitor build triggers to ensure they are functioning correctly.
- Use adequate security measures (e.g., secret tokens) for webhook endpoints.
FAQ
What is the main advantage of using webhooks over polling?
Webhooks trigger builds instantly, avoiding unnecessary polling and resource usage.
Can I use both methods together?
Yes, but it is generally not recommended as it can lead to redundant builds.
What if my SCM does not support webhooks?
You may need to rely on polling or consider migrating to an SCM that supports webhooks.