Ruby: Run Code Blocks at Specific Time Intervals
3
While working on a Rails project, some of my business logic parts need to run at specific time intervals. First, I create Rake tasks for my code blocks and use "cron" jobs to run those Rake tasks at the required time intervals. But, as you know, every Rake task loads the whole Rails application into the memory to run and this is costly, especially if my Rake tasks run at high frequency (every ~1 min).
So, I decided to load the tasks into the memory and make them sleep and run at specific time intervals. One of the great Rails gems that help me in doing this job is EventMachine, an event processing library for Ruby applications. Using it, you can define specific code blocks to run at specific times and also define a periodic timer for code blocks.
So, what I did is create one Rake task that contains EventMachine running, and defined some periodic timers to run code blocks at the required time intervals. In this case, my Rake task will be loaded into the memory and will be asleep (using EventMachine), merely running my code blocks at the defined time intervals without the need to reload.
- To install this gem:
gem install eventmachine
and then choose the required gem version from the given list. - If you need your code block to run periodically every 10 secs, create a periodic timer:
EventMachine.run { @periodic_job = EventMachine::PeriodicTimer.new(10){ # code block to run every 10 secs } } - You can cancel the periodic job at any time by calling:
@periodic_job.cancel
- Note:Do not forget to stop the event machine at the end of your periodic job, e.g. if you need your periodic job to run just 10 times:
x = 0 EventMachine.run { EventMachine::PeriodicTimer.new(0.1){ x += 1 # your code go here EventMachine.stop if x == 10 } }
Checkout the full documentation of EventMachine.
Written By:
Wael Shaban (wshaban.blogspot.com)
Comments
Post a Comment
eSpace podcast Prodcast
Archive
- September 2011
- April 2011
- March 2011
- December 2010
- November 2010
- September 2010
- August 2010
- July 2010
- June 2010
- April 2010
- March 2010
- November 2009
- October 2009
- September 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- November 2008
- October 2008
- September 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- January 2008
- April 2007
- March 2007
Latest Comments
- SpectraMind Commented on Egypt Wins UK's National Outsourcing Association Award
- Rofaida Awad Commented on Go Egypt Go!
- Different Mike Commented on Only idiots change their iPhone root password!
- Mike Commented on Only idiots change their iPhone root password!
- smile Commented on Only idiots change their iPhone root password!

