Search code examples
ruby-on-railsherokurufus-scheduler

schedule rufus-scheduler onto worker dyno on heroku


I'd like to use rufus-scheduler to have a background task run. I currently have a worker dyno for Sidekiq and would ideally just like to schedule onto that process. Testing the rufus-scheduler as per the documentation at https://github.com/jmettraux/rufus-scheduler#so-rails

require 'rufus-scheduler'

# Let's use the rufus-scheduler singleton
#
s = Rufus::Scheduler.singleton


# Stupid recurrent task...
#
s.every '1s' do
  Rails.logger.info "hello, it's #{Time.now}"
end

It comes out on both the web and worker and I'd like it to use the worker process. How would I achieve that?

Sample output is:

2014-10-17T00:30:29.382689+00:00 app[web.1]: hello, it's 2014-10-17 00:30:29 +0000
2014-10-17T00:30:29.609192+00:00 app[worker.1]: hello, it's 2014-10-17 00:30:29 +0000

Solution

  • Something like the following could do it:

    if running_on_worker_process? # you have to implement that one yourself.
      require 'rufus-scheduler'
      s = Rufus::Scheduler.singleton
      s.every '1d' do
        Rails.logger.info "taking out the garbage..."
      end
    end
    

    Beware your worker process (dyno?) going to sleep (and the scheduler with it).

    EDIT 1

    Tip: you can use the $DYNO variable (https://devcenter.heroku.com/articles/dynos#local-environment-variables) to identify which dyno you're on.

    if ENV['DYNO'].match(/^worker\./)
      # ...
    end