Grails: pass value from controller to thread

In my project, my Grails controller action creates a new thread and calls the src / groovy class folder each time this action is executed. I need to pass the value from this activity to the new thread being created. How can I achieve this?

Update: I am implementing crawler4j in my project.

My controller code looks like this: Thanks in advance.

class ResourceController{
def crawl(Integer max) {
    String crawlStorageFolder = ".crawler4j";
    String website = "www.google.com";
    controller.startNonBlocking(BasicCrawler.class, numberOfCrawlers); //this line after a series of background tasks calls the BasicCrawler class located in src/groovy. 
    Thread.sleep(30 * 1000);
}

      

crawler4j starts a new thread when the BasicCrawler class is called.

The BasicCrawler class has a visit function. I need to pass website value from ResourceController to visit function.

+3


source to share


1 answer


So, if I was doing this, I would change it so that the calling instance of the class it wants to disconnect the thread, this way it can pass any data you need, not just pass the class and instantiate the framework that's for me ... If you are using Grails 2.3+ you can simply use promises like this:

import static grails.async.Promises.*

class ResourceController {
   def crawl(Integer max) {
       Map<String,String> sharedObject = [someProperty: 'blah', someOtherProperty: 'blahblah'];
       List<Promise> promises = []
       numberOfCrawlers.times {
          promises << task {
              doSomethingOffThread( sharedObject.someProperty );
          }

          promises.last().onComplete { result -> log.info("background job done.") }
       }      
   }
}

      



Keep in mind that data shared in this manner must be read-only. Otherwise, you will have problems with concurrency. Think of this as efficient messaging, and also don't modify shared objects and you may not be dealing with synchronization. A promise can return data back to the caller via prom.get () or prom.onComplete, so there is no need to change the actual input objects.

http://grails.org/doc/2.3.0.M1/guide/async.html

0


source







All Articles