asynchronousgroovygpars

Use GPars to dispatch an async task and return immediately


I would like to have a method that dispatches an async task, and returns immediately. I don't need wait for the result. I'd like something like this to work:

/**
* runs a job and return job id for later montoring.
*/
def int runJob(){
  int jobId = createJob() // returns immediately
  task{
    doSomthingThatTakesSomeTime()
  }.then {stepResult-> doSmtgElse(stepResult)}
  return jobId
}

In the situation above, the task won't run, as there's no call for .get() , however, if I DO .get() , the method will not return jobId until task is finished.

How can i dispatch the task and still return immediately?


Solution

  • After reading @pczeus answer and Jérémie B's comment I came up with this:

    import static groovyx.gpars.dataflow.Dataflow.task
    
    def int longTask(){
        def counter = 0
        10.times {
            println "longTask_${counter}"
            counter++
            sleep 10
        }
        counter
    }
    
    def int getSomeString() {
        def jobId=55
        task {
            longTask()
    
        }.then { num -> println "completed running ${num} times" }
        return  jobId
    }
    println getSomeString()
    
    sleep 2000
    

    This prints:

    longTask_0
    55
    longTask_1
    longTask_2
    longTask_3
    longTask_4
    longTask_5
    longTask_6
    longTask_7
    longTask_8
    longTask_9
    completed running 10 times
    

    Which is what I intended: the longTask() is running in the background, the getSomeString() retruns without waiting for the long task, and as long as the program is still running (hence the sleep 2000), even the clause in the 'then' part is executed