Skip to content

Commit d905685

Browse files
committed
docs: Add timeout-inside-lock example
Explain how to place timeout() inside lock() so that queue wait time does not count against the timeout deadline. Fixes #740
1 parent 8561d98 commit d905685

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

src/doc/examples/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ If you have a question, please open a [GitHub issue](https://github.com/jenkinsc
1010
- [Locking multiple stages in declarative pipeline](locking-multiple-stages-in-declarative-pipeline.md)
1111
- [Locking a random free resource](locking-random-free-resource.md)
1212
- [Scripted vs declarative pipeline](scripted-vs-declarative-pipeline.md)
13+
- [Timeout inside lock](timeout-inside-lock.md)
1314
- [Dynamic resource pool expansion](dynamic-resource-pool-expansion.md)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Timeout Inside Lock
2+
3+
When a pipeline uses both `timeout` and `lock`, the placement of `timeout`
4+
determines whether queue wait time counts against the deadline.
5+
6+
## Problem
7+
8+
If `timeout` wraps the entire pipeline or stage, the clock starts before the
9+
lock is acquired. A job that waits a long time in the queue may time out
10+
before it gets a chance to run:
11+
12+
```groovy
13+
pipeline {
14+
agent any
15+
options {
16+
// Clock starts immediately — includes queue wait time!
17+
timeout(time: 5, unit: 'HOURS')
18+
}
19+
stages {
20+
stage('Deploy') {
21+
steps {
22+
lock('my-resource') {
23+
echo 'Deploying...'
24+
}
25+
}
26+
}
27+
}
28+
}
29+
```
30+
31+
## Solution
32+
33+
Place `timeout` **inside** `lock` so the countdown begins only after the
34+
resource has been acquired:
35+
36+
```groovy
37+
pipeline {
38+
agent any
39+
stages {
40+
stage('Deploy') {
41+
steps {
42+
lock('my-resource') {
43+
timeout(time: 5, unit: 'HOURS') {
44+
echo 'Deploying...'
45+
}
46+
}
47+
}
48+
}
49+
}
50+
}
51+
```
52+
53+
This way a job can wait in the queue as long as necessary without the
54+
timeout expiring prematurely.
55+
56+
## Stage-level variant
57+
58+
The same pattern works with `options` at the stage level:
59+
60+
```groovy
61+
pipeline {
62+
agent any
63+
stages {
64+
stage('Deploy') {
65+
options {
66+
lock('my-resource')
67+
}
68+
steps {
69+
timeout(time: 5, unit: 'HOURS') {
70+
echo 'Deploying...'
71+
}
72+
}
73+
}
74+
}
75+
}
76+
```

0 commit comments

Comments
 (0)