Sha256: 1721e2b7b94d2884347be29eec2823bd7c2c12111911317cea861f59681e8c98

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

module Clockwork
  class Event
    attr_accessor :job, :last

    def initialize(manager, period, job, block, options={})
      @manager = manager
      @period = period
      @job = job
      @at = At.parse(options[:at])
      @last = nil
      @block = block
      @if = options[:if]
      @thread = options[:thread]
      @timezone = options[:tz]
    end

    def to_s
      @job
    end

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

    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

    def thread?
      @thread
    end

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

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

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

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

    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

    def handle_error(e)
      if handler = @manager.get_error_handler
        handler.call(e)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
clockwork-0.7.0 lib/clockwork/event.rb