lib/zhong/job.rb in zhong-0.1.2 vs lib/zhong/job.rb in zhong-0.1.3

- old
+ new

@@ -29,37 +29,53 @@ def run?(time = Time.now) run_every?(time) && run_at?(time) && run_if?(time) end - def run(time = Time.now) + def run(time = Time.now, error_handler = nil) return unless run?(time) if running? @logger.info "already running: #{self}" return end @thread = nil + locked = false - ran_set = @lock.lock do + @lock.lock do + locked = true + refresh_last_ran - break true unless run?(time) + # we need to check again, as another process might have acquired + # the lock right before us and obviated our need to do anything + break unless run?(time) if disabled? @logger.info "disabled: #{self}" - break true + break end @logger.info "running: #{self}" - @thread = Thread.new { @block.call } if @block + if @block + @thread = Thread.new do + begin + @block.call + rescue => boom + @logger.error "#{self} failed: #{boom}" + error_handler.call(boom, self) if error_handler + end + nil # do not retain thread return value + end + end + ran!(time) end - @logger.info "unable to acquire exclusive run lock: #{self}" unless ran_set + @logger.info "unable to acquire exclusive run lock: #{self}" unless locked end def stop return unless running? Thread.new { @logger.error "killing #{self} due to stop" } # thread necessary due to trap context