Running a task several times at the same time as a workflow plugin

I am trying to run one task 5 times at a time using a workflow plugin. here is a snippet:

def concurrent=[:] for (int i = 0; i < 5; i++) { concurrent["concurrent${i}"] = { build job: 'test_job', parameters: [[$class: 'StringParameterValue', name:'queue', value: 'automation_prod.q'],[$class: 'StringParameterValue', name:'dummy', value: "${i}"]] } } parallel concurrent 

this snippet causes test_job to run only once. I need it to work 5 times at a time.

thanks!

+6
source share
1 answer

There are no errors in Workflow here, except for the lack of a diagnosis of errors in the script. In Groovy, the loop counter i is defined in the enclosing area and mutated, so by the time each close is complete, it has the same value: 5. You can see this, as well as the concept underlying the fix, outside of Jenkins:

 $ groovy -e 'def cs = []; for (int i = 0; i < 5; i++) {def j = i; cs += {println "${i} vs. ${j}"}}; for (c in cs) {c()}' 5 vs. 0 5 vs. 1 5 vs. 2 5 vs. 3 5 vs. 4 

In your case, Jenkins saw five attempts to plan the same downstream project with the same parameters and combined them all into one element of the queue and, thus, one of them. (Depending on the time, he may have run one line down before other build steps were even performed, in which case it would run the second line downstream, but usually it would contain less than five common assemblies.)

This new test shows that what you wanted to do is really possible; you just need to fix the current value of the loop variable in a new variable with the lexical region outside of closure.

By the way

 def cs = []; (0..4).each {i -> cs += {println i}}; cs*.call() 

works as expected from the Groovy command line since there is no mutated loop variable. Unfortunately, this syntax is not yet available in Workflow: JENKINS-26481

Be careful not to use the value of the "dummy" parameter to distinguish between entries in the queue. Although this may happen today, expect the behavior to be fixed, so that the values โ€‹โ€‹of the parameters specified by build that do not correspond to any parameter actually defined in the downstream project will either be skipped with a warning or lead to an error. If you think that you need a dummy parameter, you are probably doing something else wrong, but it is impossible to tell what it is without any explanation of why you want the downstream project to run several times and nothing in its input distinguished assembly.

+6
source

All Articles