Class: Moment::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/scheduler.rb

Direct Known Subclasses

Server

Defined Under Namespace

Classes: Event

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exit_on_idle = true) ⇒ Scheduler

Returns a new instance of Scheduler.



10
11
12
13
14
# File 'lib/scheduler.rb', line 10

def initialize(exit_on_idle = true)
  self.exit_on_idle = exit_on_idle
  @jobs = Array.new
  @now = Time.now
end

Instance Attribute Details

#exit_on_idleObject

Returns the value of attribute exit_on_idle.



7
8
9
# File 'lib/scheduler.rb', line 7

def exit_on_idle
  @exit_on_idle
end

#jobsObject (readonly)

Returns the value of attribute jobs.



8
9
10
# File 'lib/scheduler.rb', line 8

def jobs
  @jobs
end

Instance Method Details

#clean_upObject



27
28
29
# File 'lib/scheduler.rb', line 27

def clean_up
  @jobs.delete_if do |entry| entry.trigger.fire_time_after(@now).nil? end
end

#next_jobsObject

find the next wakeup triggers in our job/trigger list



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/scheduler.rb', line 56

def next_jobs
  @now = Time.now
  earliest = nil
  jobs = Array.new

  @jobs.each do |entry|
    job, trigger = entry.job, entry.trigger
    time = trigger.fire_time_after(@now)
    case
    when time.nil?
      # do nothing
    when earliest.nil?, time < earliest
      earliest = time
      jobs = [ entry ]
    when time == earliest
      jobs << entry
    end
  end

  jobs
end

#runObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/scheduler.rb', line 31

def run
  loop do
    # find the next firing triggers
    todo = next_jobs
    if todo.empty?  # nothing to do, so we wait
      break  if @exit_on_idle
      sleep
      retry  # check again if we're woken up
    end

    # sleep until the next event; if we get woken up, retry from the start
    pause_time = todo.first.trigger.fire_time_after(@now) - Time.now
    retry  if (pause_time > 0 and sleep(pause_time) < pause_time)

    todo.each do |entry|
      next  unless @jobs.index(entry)  # make sure since we were sleeping
      entry.job.execute rescue puts $!
    end

    # make sure next call to next_jobs won't return the exact same result
    sleep 0.5  # TODO this is dangerous; could skip over some jobs
  end
end

#schedule(job, trigger = nil) ⇒ Object



16
17
18
19
20
21
# File 'lib/scheduler.rb', line 16

def schedule(job, trigger = nil)
  job_id = @jobs.size
  @jobs[job_id] = Event.new(job, trigger)

  job_id
end

#unschedule(job_id) ⇒ Object



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

def unschedule(job_id)
  @jobs.delete_at(job_id)
end