Ryan Tsui Ryan Tsui - 1 month ago 16
Groovy Question

Generating parallel branches causes job to hang

I'm new to groovy and the workflow plugin, so perhaps this is something obvious. Q1: I'm try to run jobs read under a view in parallel. I do like this:

jenkins = Hudson.instance
parallel getBranches()

@NonCPS def getBranches() {
def jobBranches = [:]
for (int i = 0; i < getJobs().size(); i++) {

jobBranches["branch_${i}"] = {
build job : getJobs()[i]
}

}
return jobBranches
}

@NonCPS def getJobs() {
def jobArray = []
jenkins.instance.getView("view_A").items.each{jobArray.add(it.displayName)}
return jobArray
}


I got:

enter image description here

But if I wrote it like this:

jenkins = Hudson.instance

def jobBranches = [:]
for (int i = 0; i < getJobs().size(); i++) {

jobBranches["branch_${i}"] = {
build job : getJobs()[i]
}

}
parallel jobBranches

@NonCPS def getJobs() {
def jobArray = []
jenkins.instance.getView("view_A").items.each{jobArray.add(it.displayName)}
return jobArray
}


Then I got something like this:

enter image description here

What am I doing wrong? Or Is there another way to accomplish the same thing.

Q2: BTW, If there are three jobs, like j1, j2, j3. j1 and j2 are executed first and in parallel, when one of them are finished, j3 will be executed. so how to do this?

Answer

I figured out why.

for (int i = 0; i < getJobs().size(); i++) {
    def j=i 
    jobBranches["branch_${i}"] = {
        build job : getJobs()[j]
    }

Then it will work!