Question

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
Was it helpful?

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top