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

查看:63
本文介绍了使用 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) } :)

准确描述了发生的事情 这里.这确实是一个常见的陷阱".与其他提供函数式编程功能的语言(例如 JavaScript)一起使用.

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,比如字符串插值).

(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天全站免登陆