Sha256: a85a9ad84d396b4518c63fb9e9743325ec74541c063450f9604386a61278656c

Contents?: true

Size: 940 Bytes

Versions: 2

Compression:

Stored size: 940 Bytes

Contents

require 'securerandom'

module Slappy
  class Schedule
    class OverScheduleError < StandardError; end
    class InvalidFormatError < StandardError; end

    DEFAULT_MAX_THREAD = 1000

    def register(schedule, options = {}, &block)
      id = options[:id] || generate_id
      schedule_list[id] = Thread.new { Chrono::Trigger.new(schedule) { block.call }.run }
      Slappy.logger.try(:debug, "Schedule registerd to #{schedule}")
      id
    end

    def remove(id)
      registered = @schedule_list.include? id
      if registered
        @schedule_list[id].kill
        @schedule_list.delete id
      end
      registered
    end

    private

    def schedule_list
      @schedule_list ||= {}
    end

    def generate_id
      figure = Math.log10(DEFAULT_MAX_THREAD) + 1
      id = format("%0#{figure}d", SecureRandom.random_number(DEFAULT_MAX_THREAD))
      id = generate_id if schedule_list.include? id
      id
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
slappy-0.5.1 lib/slappy/schedule.rb
slappy-0.5.0 lib/slappy/schedule.rb