I am trying to use the worker API to speed up some tasks I am currently running sequentially. To get used to the Worker API I figured I’d just try to do something simple. Here is what I have so far:
import org.gradle.workers.WorkerExecutor
import org.gradle.workers.WorkerConfiguration
import javax.inject.Inject
// The implementation of a single unit of work
class PrintStuff implements Runnable {
String toPrint
@Inject
public PrintStuff(String fileToReverse) {
this.toPrint = toPrint
}
@Override
public void run() {
println toPrint
sleep(5000)
}
}
class PrintAll extends SourceTask {
final WorkerExecutor workerExecutor
String[] propertyValues;
@OutputDirectory
File outputDir
// The WorkerExecutor will be injected by Gradle at runtime
@Inject
public PrintAll(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor
}
@TaskAction
void printAll() {
// Create and submit a unit of work for each file
propertyValues.each { value ->
workerExecutor.submit(PrintStuff.class) { WorkerConfiguration config ->
// Use the minimum level of isolation
config.isolationMode = IsolationMode.NONE
// Constructor parameters for the unit of work implementation
config.params value
}
}
}
}
That did it! I found a few bugs I was missing as well, and now its mostly working. I just have one question. Here is my updated code:
import javax.inject.Inject
import org.gradle.workers.WorkerExecutor
import org.gradle.workers.WorkerConfiguration
// The implementation of a single unit of work
class PrintStuff implements Runnable {
String toPrint
@Inject
public PrintStuff(String toPrint) {
this.toPrint = toPrint
}
@Override
public void run() {
println toPrint
sleep(5000)
}
}
class PrintAll extends DefaultTask {
final WorkerExecutor workerExecutor
String[] propertyValues;
// The WorkerExecutor will be injected by Gradle at runtime
@Inject
public PrintAll(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor
}
@TaskAction
void printAll() {
// Create and submit a unit of work for each file
propertyValues.each { value ->
workerExecutor.submit(PrintStuff.class) { WorkerConfiguration config ->
// Use the minimum level of isolation
config.isolationMode = IsolationMode.NONE
// Constructor parameters for the unit of work implementation
config.params value
}
}
}
}
task printHope(type: PrintAll) {
propertyValues = ['value1','value2']
}
I thought this would print out the values, and then wait 5 seconds. What it is actually doing is waiting 5 seconds, then printing the values. Is this the expected behavior even though I have the print before the sleep? This doesn’t effect what I’m doing since this was just a proof of concept before I actually implemented it, but I would like to know if it’s something I can control or not.