I have a jenkins pipleine which has two triggers one for pollSCM and the other is a cron job to run every Tuesday and Thursday at 6 pm EST. I configured it as follows
triggers {
pollSCM('H/5 * * * *')
cron('00 18 * * 2,4')
}
I followed the document here to set up the trigger. The pollSCM trigger works correctly. But the cron trigger, instead of triggering the build at 6 pm EST. Its trigerring at 2 pm EST. Why is this happening?
Adding TZ (timezone) in Build periodically under Build Triggers, helped to trigger the pipeline at 6 pm EST on Tuesday and Thursday.
TZ=America/New_York
00 18 * * 2,4
Related
I'm using multibranch pipeline projects in Jenkins.
I let Jenkins index new branches.
I need Jenkins to wait until the indexing of a multibranch pipeline project is complete.
This is my current code:
def triggerScanMultibranchPipeline(projectDir, repo) {
def multibranchProject = Jenkins.instance.getItemByFullName "$projectDir/$repo"
multibranchProject.scheduleBuild()
while (multibranchProject == null || multibranchProject.isDisabled()) {
sleep 1000 //1000 milliseconds = 1 second
}
sleep time: 1, unit: 'SECONDS'
}
Already tried:
change (second) sleep to 30 seconds
This increases the duration of the build each time triggerScanMultibranchPipeline is called.
I cannot use "wait: true" for the indexing to complete, because waiting for non-job items is not supported.
See https://github.com/jenkinsci/pipeline-build-step-plugin/blob/pipeline-build-step-2.13/src/main/java/org/jenkinsci/plugins/workflow/support/steps/build/BuildTriggerStepExecution.java#L80
How can I let Jenkins wait until the branch indexing of the Multibranch Pipeline Project is complete?
I don't need cron job because the build is needed to run only once in production and not periodically.Is there a way to build the pipeline at a scheduled time without cron.
You can schedule a build using Groovy via script console or job using: scheduleBuild2:
def waittime = 100 // in secs
def jobName = 'folder/jobname' //aka it.fullName
Jenkins.instance.getItemByFullName(jobName).scheduleBuild2(waittime)
quietPeriod - seconds to wait before starting (normally 0)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Action... actions)
Description copied from interface:
ParameterizedJobMixIn.ParameterizedJob Provides a standard
implementation of SCMTriggerItem.scheduleBuild2(int,
hudson.model.Action...) to schedule a build with the ability to wait
for its result. That job method is often used during functional tests
(JenkinsRule.assertBuildStatusSuccess).
Specified by: scheduleBuild2 in interface
ParameterizedJobMixIn.ParameterizedJob<P extends
AbstractProject<P,R>,R extends AbstractBuild<P,R>> Parameters:
quietPeriod - seconds to wait before starting (normally 0) actions -
various actions to associate with the scheduling, such as
ParametersAction or CauseAction Returns: a handle by which you may
wait for the build to complete (or just start); or null if the build
was not actually scheduled for some reason
One way to do is - You can trigger it remotely
https://www.jenkins.io/doc/book/using/remote-access-api/
Let's say you got a Linux box, you can schedule it by using the "at" command
at 9:30 PM Fri
curl -X POST JENKINS_URL/job/JOB_NAME/build \
--data token=TOKEN \
--data-urlencode json='{"parameter": [{"name":"id", "value":"123"},\
{"name":"verbosity", "value":"high"}]}'
job 2 at Fri Jan 29 21:30:00 2016
Then look at it with
at -c 2
I am using a parameterized cron in my Jenkins script to run with 2 different sets of build param - one would run every 5 mins in production, and every 15 minutes in staging. The production one is running every 5 mins, but the staging one is not running. Can someone please tell me what I might be missing?
properties([
pipelineTriggers([parameterizedCron(env.BRANCH_NAME != 'master' ? '''
H/5 * * * * % environment=production
H/15 * * * * % environment=staging''' : '')]),
parameters([
choice(name: 'environment', defaultValue: 'sandbox', choices: ['sandbox', 'staging', 'production'], description: "etc")
])
])
A made a slight modification as follows and surprisingly this time only the staging one is running
properties([
pipelineTriggers([parameterizedCron('''H/2 * * * * % environment=production'''), parameterizedCron('''H/4 * * * * % environment=staging''')]),
parameters([
choice(name: 'environment', defaultValue: 'sandbox', choices: ['sandbox', 'staging', 'production'], description: "etc")
])
])
I can't find the reason why either is working half-way only.
Can someone please tell me what can be changed to fix the issue?
It's possible that H/5 schedule overwrites the H/15 schedule because there is a conflict between them, so it's unclear what parameters should be used e.g. at 15th minute. (You probably want two runs with different parameters, but not clear if the plugin understands that.)
You can try specifying that exactly:
pipelineTriggers([parameterizedCron(env.BRANCH_NAME != 'master' ? '''
0,5,10,15,20,25,30,35,40,45,50,55 * * * * % environment=production
0,15,30,45 * * * * % environment=staging''' : '')]),
Looks like there is a known bug that's open https://issues.jenkins-ci.org/browse/JENKINS-49921. It's possible to space out the runs as suggested in the bug itself as a workaround.
This worked for me
pipelineTriggers([parameterizedCron('''
# Every 10 mins in production
*/10 * * * * %environment=production
# Every 22 minutes in staging
*/22 * * * * %environment=staging
''' : '')])
I have the following code in groovy Jenkinsfile:
def current = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss.SSSZ').parse(currenttime.trim())
println current
def end_date = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss.SSSZ').parse(scheduled_end_date.trim())
println end_date
schedule_grace_period_validity = current - end_date > 5 ? false : true
the output for this is :
Tue Feb 27 13:20:54 EST 2018
[Pipeline] echo
Mon Dec 18 18:00:00 EST 2017
[Pipeline] echo
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DateGroovyMethods minus java.util.Date java.util.Date
This works just fine in my local box but in sandbox mode in Jenkins, this fails and I can't turn off the sandbox mode in Jenkins.
IS there any workaround for this ?
The simplest way is to go to /scriptApproval/ page in your Jenkins instance and approve the signature. When you get this exception after running your script you will see something like this in the script approval page:
Just click Approve and run your script again.
Alternatively you could try calculating difference between two dates in days as:
int diff = BigDecimal.valueOf((current.time - end_date.time) / 86400000).setScale(0, java.math.RoundingMode.UP).intValue()
but in this case you may also run into RejectedAccessException. I tried to run it in Groovy sandbox in my local Jenkins instance and I got this:
[Pipeline] End of Pipeline
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.util.Date getTime
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:175)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor$6.reject(SandboxInterceptor.java:261)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:381)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:284)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checke
How can I exclude specific days from a Jenkins scheduld?
For example: every 5 minutes from 7 to 17 and from monday to friday.
H/05 7-17 * * 1-5
But, if the day of the week is a public holiday, it should not run. How can I configure this?
Thx
Currently Jenkins crontab does not support a complicate logic such public holidays exclusion. However, there are some options out there you can use to accomplish that:
First
For my project I create my own holiday database, which it is a file containing the days I want to exclude eg.:
# /path/to/holidays
# New Year's Day
01-01-2017
# Christmas
12-25-2017
and I check it using a Jenkins shell script, as it was proposed here.
For example for the above file format:
#!/bin/bash
TODAY="`date +%m-%d-%Y`"
if grep -q $TODAY /path/to/holidays; then
echo Skipping holiday for $*
exit 0
fi
$*
Second
A more robust solution but more complicate is to create your own plugin based on the
Run Condition Example Plugin in which you exclude the public holidays of your Country such as this plugin.
There is another option now, with the Jenkins Working Hours Plugin.
Using the plugin, you can configure both working hours:
Or Holidays as 'Excluded Days':
The working hours plugin allows you to set up a schedule of allowable build times; projects can opt in to use the schedule to prevent them from running outside of configured allowable build times. If a build is scheduled during non-working hours then it is kept in the build queue until the next allowable time.
Jobs opt in via the enforceBuildSchedule job parameter, which is provided by this plugin. It can optionally take in a branches parameter to limit it's usage to only those branches. This only works in MultiBranchPipelines.
Usage
Sample job (scripted pipeline):
node {
properties([enforceBuildSchedule()])
stage('Do some stuff') {
echo 'this can wait til morning'
}
}
Sample job (declarative pipeline):
pipeline {
agent any
options {
enforceBuildSchedule()
}
stages {
stage('Do some stuff') {
steps {
echo 'this can wait til morning'
}
}
}
}
Sample job with branches parameter (works in both declarative and scripted):
node {
properties([enforceBuildSchedule(branches: ['dev', 'qa', 'prod')])
stage('Do some stuff') {
echo 'this can wait til morning'
}
}
Using the idea of one of the answers and using Declarative + Script block I created this:
stage('Check if Today is Holiday') {
steps {
// Based on idea from https://stackoverflow.com/a/41219757/7820857
script {
IS_HOLIDAY = sh(script: 'grep -q $(date +%Y-%m-%d) /etc/holidays', returnStatus: true)
if (IS_HOLIDAY == 0) {
currentBuild.result = 'ABORTED'
error ('Today is Holiday according to the file /etc/holidays inside the Jenkins server')
}
}
}
}
This will depend on the file /etc/holidays inside the Jenkins server. Adding this additional Stage before will help you to identify if the day mentioned is holiday and exit with error message, or not and continue with the rest of the stages.
I will like that the Working Hours Plugin worked for this but they queue the jobs in case that the day is inside the Excluded days, but I need to cancel the job execution. A feature request exist for that user case.