lib/zhong/scheduler.rb in zhong-0.1.9 vs lib/zhong/scheduler.rb in zhong-0.2.0

- old
+ new

@@ -1,25 +1,23 @@ module Zhong class Scheduler - attr_reader :config, :redis, :jobs, :logger + extend Forwardable + def_delegators Zhong, :redis, :tz, :logger, :heartbeat_key + attr_reader :jobs + DEFAULT_CONFIG = { timeout: 0.5, grace: 15.minutes, - long_running_timeout: 5.minutes, - tz: nil, - heartbeat_key: "zhong:heartbeat", + long_running_timeout: 5.minutes }.freeze def initialize(config = {}) @jobs = {} @callbacks = {} @config = DEFAULT_CONFIG.merge(config) - @logger = @config[:logger] - @redis = @config[:redis] - @tz = @config[:tz] @category = nil @error_handler = nil @running = false end @@ -42,11 +40,11 @@ end def every(period, name, opts = {}, &block) raise "must specify a period for #{name} (#{caller.first})" unless period - job = Job.new(name, opts.merge(@config).merge(every: period, category: @category), &block) + job = Job.new(name, opts.merge(@config).merge(every: period, category: @category), @callbacks, &block) raise "duplicate job #{job}" if jobs.key?(job.id) @jobs[job.id] = job end @@ -55,11 +53,14 @@ @error_handler = block if block_given? @error_handler end def on(event, &block) - raise "unknown callback #{event}" unless [:before_tick, :after_tick, :before_run, :after_run].include?(event.to_sym) + unless [:before_tick, :after_tick, :before_run, :after_run, :before_disable, + :after_disable, :before_enable, :after_enable].include?(event.to_sym) + raise "unknown callback #{event}" + end (@callbacks[event.to_sym] ||= []) << block end def start logger.info "starting at #{redis_time}" @@ -110,13 +111,13 @@ def find_by_name(job_name) @jobs[Digest::SHA256.hexdigest(job_name)] end def redis_time - s, ms = @redis.time # returns [seconds since epoch, microseconds] + s, ms = redis.time # returns [seconds since epoch, microseconds] now = Time.at(s + ms / (10**6)) - @tz ? now.in_time_zone(@tz) : now + tz ? now.in_time_zone(tz) : now end private TRAPPED_SIGNALS = %w(QUIT INT TERM).freeze @@ -142,10 +143,10 @@ fire_callbacks(:after_run, job, time, ran) end def heartbeat(time) - @redis.hset(config[:heartbeat_key], heartbeat_field, time.to_i) + redis.hset(heartbeat_key, heartbeat_field, time.to_i) end def heartbeat_field @heartbeat_field ||= "#{`hostname`.strip}##{Process.pid}" end