Search code examples
ruby-on-railsrufus-scheduler

Can I schedule controller methods in rails using rufus-scheduler?


Could I schedule the index method from the controller posted below? If so, how would I go about doing that?

class WelcomeController < ApplicationController
  def index
   if Number.find(1)
    @number = Number.first
    @number.value += 1
    @number.save
   else 
    @number = Number.new    
    @number.value = 0
   end
  end
end

Solution

  • So you seem to have a Number model. The first step would be to move your logic from the controller to the model:

    class Number
    
      def self.increment
    
        n = nil
    
        if Number.find(1)
          n = Number.first
          n.value += 1
          n.save
        else
          n = Number.new
          n.value = 0
        end
    
        n
      end
    end
    

    Your controller then becomes

    class WelcomeController < ApplicationController
    
      def index
    
        @number = Number.increment
      end
    end
    

    Then this "increment" class method can be called from the scheduler too. Like in:

    # file:
    # config/initializers/scheduler.rb
    
    require 'rufus-scheduler'
    
    # Let's use the rufus-scheduler singleton
    #
    s = Rufus::Scheduler.singleton
    
    
    # Stupid recurrent task...
    #
    s.every '10m' do
    
      Number.increment
    end
    

    Now if this answer too goes way above your head, consider registering for a Rails developer course. Please realize that people are here to help you, not to do your job for free.