Class: Clockwork::Event

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(period, job, block, options = {}) ⇒ Event



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

def initialize(period, job, block, options={})
  @period = period
  @job = job
  @at = At.parse(options[:at])
  @last = nil
  @block = block
  if options[:if]
    if options[:if].respond_to?(:call)
      @if = options[:if]
    else
      raise ArgumentError.new(':if expects a callable object, but #{options[:if]} does not respond to call')
    end
  end

  if options[:thread]
    @thread = options[:thread]
  end

  @timezone = options[:tz] || Clockwork.config[:tz]
end

Instance Attribute Details

#jobObject

Returns the value of attribute job.



56
57
58
# File 'lib/clockwork.rb', line 56

def job
  @job
end

#lastObject

Returns the value of attribute last.



56
57
58
# File 'lib/clockwork.rb', line 56

def last
  @last
end

Instance Method Details

#convert_timezone(t) ⇒ Object



83
84
85
# File 'lib/clockwork.rb', line 83

def convert_timezone(t)
  @timezone ? t.in_time_zone(@timezone) : t
end

#exception_message(e) ⇒ Object



126
127
128
129
130
131
132
133
134
135
# File 'lib/clockwork.rb', line 126

def exception_message(e)
  msg = [ "Exception #{e.class} -> #{e.message}" ]

  base = File.expand_path(Dir.pwd) + '/'
  e.backtrace.each do |t|
    msg << "   #{File.expand_path(t).gsub(/#{base}/, '')}"
  end

  msg.join("\n")
end

#executeObject



116
117
118
119
120
# File 'lib/clockwork.rb', line 116

def execute
  @block.call(@job)
rescue => e
  log_error e
end

#log_error(e) ⇒ Object



122
123
124
# File 'lib/clockwork.rb', line 122

def log_error(e)
  Clockwork.config[:logger].error(e)
end

#run(t) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/clockwork.rb', line 101

def run(t)
  t = convert_timezone(t)
  @last = t

  if thread?
    if thread_available?
      Thread.new { execute }
    else
      log_error "Threads exhausted; skipping #{self}"
    end
  else
    execute
  end
end

#thread?Boolean



93
94
95
# File 'lib/clockwork.rb', line 93

def thread?
  @thread
end

#thread_available?Boolean



97
98
99
# File 'lib/clockwork.rb', line 97

def thread_available?
  Thread.list.count < Clockwork.config[:max_threads]
end

#time?(t) ⇒ Boolean



87
88
89
90
91
# File 'lib/clockwork.rb', line 87

def time?(t)
  t = convert_timezone(t)
  elapsed_ready = (@last.nil? or (t - @last).to_i >= @period)
  elapsed_ready and (@at.nil? or @at.ready?(t)) and (@if.nil? or @if.call(t))
end

#to_sObject



79
80
81
# File 'lib/clockwork.rb', line 79

def to_s
  @job
end