Class: DaemonKit::Cron

Inherits:
Object show all
Defined in:
lib/daemon_kit/cron.rb

Overview

Thin wrapper around rufus-scheduler gem, specifically designed to ease configuration of a scheduler and provide some added simplicity. It also logs any exceptions that occur inside the scheduled blocks, ensuring your code isn’t running blind.

For more information on rufus-scheduler, please visit the RDoc’s at rufus.rubyforge.org/rufus-scheduler/

To use the evented scheduler, call #DaemonKit::EM.run prior to setting up your first schedule.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCron

Returns a new instance of Cron.



53
54
55
56
57
58
59
# File 'lib/daemon_kit/cron.rb', line 53

def initialize
  @scheduler = Rufus::Scheduler.start_new

  def @scheduler.handle_exception( job, exception )
    DaemonKit::Cron.instance.handle_exception( job, exception )
  end
end

Instance Attribute Details

#exception_handlerObject

Returns the value of attribute exception_handler.



19
20
21
# File 'lib/daemon_kit/cron.rb', line 19

def exception_handler
  @exception_handler
end

#schedulerObject (readonly)

Returns the value of attribute scheduler.



18
19
20
# File 'lib/daemon_kit/cron.rb', line 18

def scheduler
  @scheduler
end

Class Method Details

.handle_exception(job, exception) ⇒ Object

Define a block for receiving exceptions from inside the scheduler



33
34
35
# File 'lib/daemon_kit/cron.rb', line 33

def handle_exception( &block )
  instance.exception_handler = block
end

.instanceObject



23
24
25
# File 'lib/daemon_kit/cron.rb', line 23

def instance
  @instance ||= new
end

.runObject

Once the scheduler has been configured, call #run to block the current thread and keep the process alive for the scheduled tasks to run



42
43
44
45
46
47
48
49
50
# File 'lib/daemon_kit/cron.rb', line 42

def run
  DaemonKit.logger.info "Starting rufus-scheduler"

  if instance.is_a?( Rufus::Scheduler::PlainScheduler )
    instance.scheduler.join
  else
    Thread.stop
  end
end

.schedulerObject

Access to the scheduler instance



28
29
30
# File 'lib/daemon_kit/cron.rb', line 28

def scheduler
  instance.scheduler
end

Instance Method Details

#handle_exception(job, exception) ⇒ Object



61
62
63
64
65
# File 'lib/daemon_kit/cron.rb', line 61

def handle_exception( job, exception )
  DaemonKit.logger.error( "Cron: job #{job.job_id} caught exception: '#{exception}'" )
  DaemonKit.logger.exception( exception )
  @exception_handler.call( job, exception ) unless @exception_handler.nil?
end