Search code examples
ruby-on-railsrails-activerecorddaemonbackground-process

Start a background Rails process at system boot


I'd like to have a background process that will always run, preferably starting whenever the server boots up. This process will be in charge of periodically polling network devices and save the results in Active Record for access by the Rails application, so from what I understand it would need to be a part of the rails application (so that it has access to Active Record)

In rails, how can I specify that something should start running when server boots up? If I use https://github.com/thuehlinger/daemons and call my process with ruby myserver_control.rb start when my server starts, will that process have access to Active Record?


Solution

  • You can use the clockwork gem to run a job periodically.

    example lib/clock.rb where you schedule jobs

    require 'rake'
    require 'clockwork'
    require File.expand_path('../../config/boot',        __FILE__)
    require File.expand_path('../../config/environment', __FILE__)
    
    module Clockwork
      configure do |config|
        config[:sleep_timeout] = 60
      end
    
      every(10.minutes, 'inbox:process_all') do
        `rake inbox:process_all`
      end
      every(1.day, 'email:send_daily_summary', at: '00:00') do
        `rake email:send_daily_summary`
      end
    end