I schedule a job using Rufus-scheduler in Ruby from a simple controller's action. Later I want to call another action in which I will un-schedule the job that was executing up until that moment in time. Of course, I need to keep a reference to my scheduler alive during many sessions that may occur between starting and stopping the scheduler. An obvious choice would be some kind of a singleton class which would keep that reference to the scheduler.
Is that an OK approach?
If yes, here is how I handled it...
Beside folders like 'controllers', 'models', 'views'... I created folder 'domain' in which I created AppConfig singleton class that has property of class Rufus::Scheduler.
My singleton class looks like this:
require 'singleton'
require 'rufus/scheduler'
class AppConfig
include Singleton
attr_accessor :scheduler
def self.instance
@@instance ||= new
end
def initialize
@scheduler = Rufus::Scheduler.start_new
end
end
And my actions that use this scheduler are like this:
# ...
# someController
def start_actions
scheduler = AppConfig.instance.scheduler
scheduler.every('30s') do
SomeModel.some_method
end
end
def stop_actions
scheduler = AppConfig.instance.scheduler
scheduler.stop(:terminate => true)
end
Am I missing something here? Is this an OK approach?
the problem I see with your approach: when you stop the scheduler, @@instance doesn't become nil, so the next time the controller needs a scheduler it will get one, the same one, which is stopped.
Most of the time, people start a scheduler in config/initializers/scheduler.rb and place it in a global var (or a singleton). That scheduler lives as long as the Ruby on Rails process lives. The controller place (or remove) jobs in the scheduler, they never stop it.