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

Returns a new instance of Event.



7
8
9
10
11
12
13
# File 'lib/clockwork.rb', line 7

def initialize(period, job, block, options={})
	@period = period
	@job = job
	@at = parse_at(options[:at])
	@last = nil
	@block = block
end

Instance Attribute Details

#jobObject

Returns the value of attribute job.



5
6
7
# File 'lib/clockwork.rb', line 5

def job
  @job
end

#lastObject

Returns the value of attribute last.



5
6
7
# File 'lib/clockwork.rb', line 5

def last
  @last
end

Instance Method Details

#exception_message(e) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/clockwork.rb', line 36

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

#log_error(e) ⇒ Object



32
33
34
# File 'lib/clockwork.rb', line 32

def log_error(e)
	STDERR.puts exception_message(e)
end

#parse_at(at) ⇒ Object

Raises:



47
48
49
50
51
52
53
54
# File 'lib/clockwork.rb', line 47

def parse_at(at)
	return unless at
	m = at.match(/^(\d\d):(\d\d)$/)
	raise FailedToParse, at unless m
	hour, min = m[1].to_i, m[2].to_i
	raise FailedToParse, at if hour >= 24 or min >= 60
	[ hour, min ]
end

#run(t) ⇒ Object



25
26
27
28
29
30
# File 'lib/clockwork.rb', line 25

def run(t)
	@last = t
	@block.call(@job)
rescue => e
	log_error(e)
end

#time?(t) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
# File 'lib/clockwork.rb', line 19

def time?(t)
	ellapsed_ready = (@last.nil? or (t - @last).to_i >= @period)
	time_ready = (@at.nil? or (t.hour == @at[0] and t.min == @at[1]))
	ellapsed_ready and time_ready
end

#to_sObject



15
16
17
# File 'lib/clockwork.rb', line 15

def to_s
	@job
end