Cronjob every day except the last 5 days of the month

Viewed 25

Currently, I run a job via cronjob, which starts every day at 4AM. Now the exception has been added that it should not run the last 5 days of the month.

What would the cron syntax look like if the exception was included?

currently: 0 0 4 * * *

1 Answers

Given different months have a different number of days, I don't think this can be done just with Cron. As a workaround, you can create the cron expression on the fly like below. This will make sure the correct cron is set for each month.

def maxDaysForMonth = java.time.LocalDate.now().getMonth().maxLength()
def expression = "0 4 1-" + (maxDaysForMonth-5) + " * *"

pipeline {
    agent any
    triggers{ cron(expression) }
    stages {
        stage('Build') {
            steps {
                script {
                    echo "Build"
                    echo "$expression"
                }
           }
        }
    }
}
Related