使用for循环的并行jenkins作业 [英] Parallel jenkins job using a for loop

查看:114
本文介绍了使用for循环的并行jenkins作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环并行运行构建列表,因为代码越来越大.

I am trying to run a list of builds in parallel using a for loop because the code is getting bigger and bigger.

我有一个包含项目名称的全局列表

I have a global list with the names of projects

@Field def final String[] projectsList = ['project1','project2', 'project3'....]
stages {
    stage('Parallel Build') {
        steps{
            script{
                   def branches = [:]
                   for(int i = 0;i<15;i++) {
                        branches["Build "+projectsList[i]] = {buildProject(i)}
                   }
                   parallel branches
             }
     }

}           

Build projects方法从全局列表中获取项目的名称,并使用maven进行构建.

The Build projects method takes the name of the project from the global list and builds it using maven.

问题是,索引15(不应构建)的项目正在并行构建15次.好像在等待for循环结束,然后在这种情况下将相同的可用i值(15)分配给所有方法.

The thing is, the project at index 15 (Which shouldn't be built) is building 15 times in parallel. As if it is waiting until the for loop ends and then assigns the same available i value (15) in this case to all the methods.

您知道我该如何解决吗?

Do you have any idea how can I solve this ?

推荐答案

您的问题在于您如何(错误地)使用Groovy闭包概念,即您在循环体中定义闭包的那一部分迭代变量 i ,即 {buildProject(i)} :)

Your issue lies with how you make (mis)use of the Groovy closure concept, i.e. the part where you define a closure in the loop's body that makes use of the iteration variable i, that is { buildProject(i) } :)

What happens exactly is nicely described here. This is, indeed, a common "gotcha" with other languages offering functional programming features, as well (e.g. JavaScript).

最简单(虽然几乎不是最优雅)的解决方案是在循环内定义一个变量 ,该变量接收当前的 i 值并在闭包内使用该值:

The easiest (hardly the most elegant, though) solution is to define a variable within the loop that receives the current i value and make use of that within the closure:

def branches = [:]
for(i = 0; i < 15; i++) {
    def curr = i
    branches["Build ${projectsList[i]}"] = { buildProject(curr) }
}
parallel branches

(我还使用了一些惯用的Groovy,例如String插值法.)

(I've also used a bit more idiomatic Groovy like String interpolation).

迭代一系列项目的更优雅,更简洁,类似于Groovy的解决方案是:

A more elegant, less verbose, Groovy-like solution that iterates through the range of projects would be:

(0..<projectsList.size()).each { i ->
    branches["Build ${projectsList[i]}"] = { buildProject(i) }
}

这篇关于使用for循环的并行jenkins作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆