pipeline中,可以通过parallel,并行跑多个job。但是如果想限制并行跑的job个数,应该如何做呢?
比如说有10个job,要并行跑,但是目前资源有限,只允许最多3个同时跑,那这种情况下,应该如何修改Jenkinsfile,来满足这个需求?
通过自己的摸索,发现用以下方法,可以实现。
下图有6个job,test1-test6,这6个job,是希望并行跑的,但是在一个时刻,最多只有2个job能够并行跑。

直接上Jenkinsfile代码:
pipeline {
agent any
stages {
stage("parallel test") {
steps {
script {
def branches = [:]
MAX_CONCURRENT = 2
//创建fifo
latch = new java.util.concurrent.LinkedBlockingDeque(MAX_CONCURRENT)
//往fifo中,填入最大个数元素
for(int i=0; i<MAX_CONCURRENT; i++)
latch.offer("$i")
def job_list = [
"test1",
"test2",
"test3",
"test4",
"test5",
"test6"
]
for(int i=0; i<job_list.size(); i++) {
def name = job_list[i]
branches[name] = {
def thing = null
waitUntil {
//获取一个资源
thing = latch.pollFirst();
return thing != null;
}
try {
//执行job
build(job: name, propagate: false)
}
finally {
//释放一个资源
latch.offer(thing)
}
}
}
timestamps {
parallel branches
}
}
}
}
}
}
本质上,利用了java的LinkedBlockingDeque这个类,以下网站是介绍这个类:
http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/LinkedBlockingDeque.html
将以上代码,写入到pipeline job配置的pipeline选项框中,注意,不能勾选Use Groovy Sandbox。
当然也可以把代码,写入到Jenkinsfile文件中,然后执行job需要执行的Jenkinsfile即可。

执行log如下,test1和test2首先执行,能够获取到资源,得到执行,之后的job,获取不到资源,然后被阻塞。

test1和test2执行完毕后,会释放资源,test3和test4获取到资源,然后开始执行。

执行完后,blueocean显示如下:

从blueocean看出,test1和test6是并行执行的,但是在真实环境中,他们并不是同时执行的。
网友评论