Riccardo79
Riccardo79

Reputation: 1046

Jenkins cron check

I need a groovy snippet in order to check that user scheduled the current job just to run once (for example '30 11 21 01 *')

Is there a way to get in the pipeline the cron string?

pipeline {
  agent any
  stages {
    stage('run_upgrade') {
        
        ... CHECK CRON STRING ...
        
        when {
          beforeAgent true
          triggeredBy 'TimerTrigger'
        }
     }
}

I cannot use others cron plugins. The instance is locked

Riccardo

Upvotes: 0

Views: 1426

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6824

You can get the cron configurations by accessing the project item itself and retrieving all triggers configuration from which you can extract the cron spec definition for each trigger.
Something like Jenkins.instance.getItem('YOUR_JOB_NAME').getTriggers()

In your case you can run something like the following in your pipeline:

pipeline {
    agent any
    stages {
        stage('Check Cron Spec'){
            steps{
                script {
                    Jenkins.instance.getItem(JOB_NAME).getTriggers().each{
                        // Validate the trigger is indeed a timer and if so print the cron string (spec)
                        if (it.key =~ 'TimerTrigger') { 
                           println it.value.spec  
                           // Here you can validate the value
                        }
                    }  
                }
            }
        }
    }
}

Notice: you will probably receive a Scripts not permitted to use method when executing this script and an administrator will have to approve the signature of these methods.

Upvotes: 1

Related Questions