Wednesday, 16 July 2008

Ruby: Run Code Blocks at Specific Time Intervals

While working in Rails project, some of my business logic parts need to run at specific time intervals. First, I created a 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 specially 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 helps me doing this job is EventMachine. It is event processing library for Ruby applications. Using it you can define specific code blocks to run at specific time and also define a periodic timer for code blocks that will run periodically.

So, what I did is creating one rake task contains the event machine 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 sleep (using the event machine) and run my code blocks at the defined time intervals.

  • To install this gem:

    gem install eventmachine

    and then choose the required gem version from the given list.

  • If you need some 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.