Can I schedule controller methods in rails using r

2019-05-20 15:08发布

问题:

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

回答1:

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.



回答2:

first you need to initialize a rufus-scheduler instance. This is usually done in a Rails initializer:

# config/initializers/scheduler.rb

require 'rufus-scheduler'

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

# Stupid recurrent task...
#
s.every '1m' do

  Rails.logger.info "hello, it's #{Time.now}"
end

Your controller can then use the rufus-scheduler instance, as in:

class ScheController < ApplicationController

  def index

    job_id =
      Rufus::Scheduler.singleton.in '5s' do
        Rails.logger.info "time flies, it's now #{Time.now}"
      end

    render :text => "scheduled job #{job_id}"
  end
end

This works well with Webrick and Thin, but requires some tuning with Passenger or Unicorn (preventing multiple schedulers and/or preventing the initial rufus-scheduler thread from vanishing).