Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run something async in Grails 2.3

In My Grails service, there is a part of a method I wish to run asynchronously.

Following, the doc for 2.3.x http://grails.org/doc/2.3.0.M1/guide/async.html

I do

public class MyService {
    public void myMethod() {
        Promise p = task {
            // Long running task
        }
        p.onError { Throwable err ->
            println "An error occured ${err.message}"
        }
        p.onComplete { result ->
            println "Promise returned $result"
        }
        // block until result is called
        def result = p.get()
    }
}

However, I want to execute mine without any blocking. The p.get() method blocks. How do I execute the promise without any sort of blocking. I don't care if myMethod() returns, it is a kinda of fire and forget method.

like image 529
More Than Five Avatar asked Aug 12 '14 18:08

More Than Five


1 Answers

So, according to the documentation if you don't call .get() or .waitAll() but rather just make use of onComplete you can run your task without blocking the current thread.

Here is a very silly example that I worked up in the console to as a proof of concept.

import static grails.async.Promises.*
def p = task {
    // Long running task
    println 'Off to do something now ...'
    Thread.sleep(5000)
    println '... that took 5 seconds'
    return 'the result'
}

p.onError { Throwable err ->
    println "An error occured ${err.message}"
}
p.onComplete { result ->
    println "Promise returned $result"
}

println 'Just to show some output, and prove the task is running in the background.'

Running the above example gives you the following output:

Off to do something now ...  
Just to show some output, and prove the task is running in the background.  
... that took 5 seconds   
Promise returned the result
like image 92
Joshua Moore Avatar answered Sep 19 '22 13:09

Joshua Moore