Reputation: 4611
I am using Jenkins Declarative Pipeline and wonder whether if there is any way to trigger specific stage only periodically or not.
What I mean when we checkout SCM, pipeline triggers but Stage 2 takes too long for some of our projects.Thus rather than waiting this stage I would like to run this stage only daily basis but still keep this stage in jenkinsfile.
Is there any way to achieve this? What might be the best approach of doing this?
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
triggers {
cron('H H 0 0 0')
}
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
steps {
script {
// do something
)
}
}
}
Upvotes: 1
Views: 3169
Reputation: 3076
Please see below code / method which will give you an idea of how to execute specific stage at a specific day or at a specific condition.You can change the conditions based on your requirement
Use plugin Timestamper https://plugins.jenkins.io/timestamper/ to get timestamp releated infos.
# Get the day from the build timestamp
def getday = env.BUILD_TIMESTAMP
getday = getday .split(" ")
// Extract current day
getday = getday [3]
pipeline
{
agent any
options { timestamps () }
stages {
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
when
{
// Note: You can change condition as per your need
// Stage will run only when the day is Mon
expression {
getday == "Mon"
}
}
steps {
script {
// do something
)
}
}
}
}
Configure BuildTimestamp:
If your build time stamp is not configured to get day information, then you can do it using below method
https://plugins.jenkins.io/build-timestamp/
Manage Jenkins -> Configure System -> Build Timestamp -> Click on Enable BUILD_TIMESTAMP.
Put Pattern as :yyyy-MM-dd HH:mm:ss z EEE
Please note : Triggeres directive is available in jenkins pipeline as shown below where you could put your cron condition but it will be executed for all the stages and not for a single stage.
// Declarative //
pipeline {
agent any
triggers {
cron('H H 0 0 0')
}
stages {
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
}
}
Upvotes: 3