Is it possible to pause a stage until a time is reached in a Jenkins declarative pipeline?

Viewed 3371

I have a requirement to only allow deployments to production in a specific time range, e.g.: between 04:00 and 06:00.

My Jenkins pipeline is triggered by a Git webhook and starts a flow consisting of the usual stages (Build, Test, Deploy Dev, Deploy Pre, Deploy Pro).

When we reach the Deploy Pro stage I would need to check whether the current time is in the allows range to go on. Otherwise I need to pause the pipeline (freeing the Jenkins agent) until that time range is reached.

Is is possible to implement this? How?

2 Answers

To do this, you can use sleep method, which can get different units: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS (by default it's SECONDS).

E.g. sleep(time:3,unit:"SECONDS") (or just sleep 3 - it's the same).

So, check whether the current time is in the allows range, and if it's not, then specify time for sleep method as value of 04:00 - <current time> (you need to use some arithmetics here to get right value in seconds or minutes, but it shall be not hard).

But if all the other stages are quite fast, I recommend you to use Poll SCM option (with specifying time range) for all pipeline, because it's much more easier and the result will be the same - job will be finished only after 04:00.

Your Jenkins pipeline is triggered by a Git webhook and starts a flow consisting of the usual stages (Build, Test, Deploy Dev, Deploy Pre, Deploy Pro).

Option 1: skip the deployment using 'when' condition and if time is not between

Option 2: separate the pipelines for CI and CD And CD will trigger only during that or keep in pause stage using shell cmd

Related