Ever need to suspend a task or a small job in Ruby (rails included) ? Of course you do. I won’t get into the lengthy discussion about green-threads in Ruby and yes Ruby is single threaded, JRuby can and does use JVMs java.lang.Thread , in fact there is a very handy safe class you should use “ScheduledThreadPoolExecutor”.
I love the existence of this very very handy gem, it covers most of the situations for you to “call and forget” when it comes to asynchronous tasks. It is based on the concept of Actors and Watchers(Observers). In fact it reminds me of Java’s AOP but it’s not it.
This gem is super easy to use.
- Obviously add it to gemfile
- Add “include Celluloid” to your class and …
- call “async.<method of that class” and
Celluloid will handle the rest, it’ll figure out if it needs to use fiber, fork or java’s thread.
You can observe and control your actors or just leave it.
Here is the tip, sometimes we need to execute rake task (say scheduled task) , you would assume that celluloid will work just fine. it WON’T.
What happens is that rake will shutdown the process and cellulo”id” method will never be execute AND you won’t get an error.
How to make it work?
simple, just add “require ‘celluloid/autostart'” to your rake file and everything will be asynchronously run.
Thanks & hope it helps