Search code examples
ruby-on-railsamazon-ec2delayed-jobrufus-scheduler

Issue with rufus-scheduler when we have multiple EC2 instances


I have deployed rails app on two EC2 instances. I have scheduled on Job with rufus-scheduler to run every 24 hours to send some emails.

But scheduler is running separately on two instances.

I need run scheduler on only one instance. So can you please help with this issue?

Thanks


Solution

  • Let's assume you've followed https://github.com/jmettraux/rufus-scheduler#so-rails

    You could modify the initializer in this way:

    #
    # config/initializers/scheduler.rb
    
    require 'rufus-scheduler'
    
    s = Rufus::Scheduler.singleton
    
    unless File.exist?(File.dirname(__FILE__) + '/../../no_scheduling')
    
      s.every '1m' do
        Rails.logger.info "hello, it's #{Time.now}"
      end
    end
    

    Then in the Rails root of the instance you don't want to schedule, simply touch the no_scheduling file, then start your Rails. The instances with a "no_scheduling" file will not schedule.

    Exercise 1: enhance the initializer above so that it doesn't even instantiate the scheduler if no_scheduling is present.

    Exercise 2: replace the file check by an IP check so that only the rails setup on a given IP schedules.