Friday 6 February 2009

BackgroundRb and Synchronous calls

BackgroundRb lets you also call the workers synchronously. This is quite neat as you can use it as a form of pseudo-proxy and all other kinds of goodies.
But, the documentation is lacking, so I am posting this for all you frustrated Googlers out there. Here is what you need to do.

class SampleWorker < BackgrounDRb::MetaWorker
set_worker_name :sample_worker

def create(args = nil)
# this method is called, when worker is loaded for the first time
end

def test_me args
puts "test_me 1 (puts)"
logger.debug("test_me hit (log)")
return "of course it works"
end
end


Now, the BackgroundRb site tells you to call this like so to get a response back:

MiddleMan.worker(:sample_worker).test_me(:arg => "1")


This, in fact, won't work.

You need to do this:

MiddleMan.worker(:sample_worker).test_me({:arg => "1"}, true)


The second parameter (and make sure you put {} around your first set of args) is some freaky boolean to say, "no, seriously, I want a result back". Otherwise you get nil.

Bonus Tip!
When you define a method in a worker it HAS to accept arguments.
This won't work:
def test_me
end


This will:

def test_me(something = 1)
end

2 comments:

gnufied said...

Aren't you using slightly old version, because "true" is no longer necessary and all calls are by default synchronous.

Also, if you want asynchronous calls you can append async_xx in front of method name and make an asynchronous call.

Phil Smy said...

I don't think I am - I just got the code the other day!

Yes, asynch is easy... not many people use it for synchronous calls though.

Thanks for posting!