Class: Later::Schedule

Inherits:
Object
  • Object
show all
Defined in:
lib/later.rb

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Schedule

Returns a new instance of Schedule.



8
9
10
11
12
13
14
# File 'lib/later.rb', line 8

def initialize(key)
  if key.is_a?(Nest)
    @key = key
  else
    @key = Later.key[key]
  end
end

Instance Method Details

#[](event) ⇒ Object



24
25
26
# File 'lib/later.rb', line 24

def [](event)
  Time.at key[:schedule].zscore(event) rescue nil
end

#countObject



28
29
30
# File 'lib/later.rb', line 28

def count
  key[:schedule].zcard
end

#each(&block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/later.rb', line 44

def each(&block)
  @stop = false

  loop do
    break if @stop

    time = Time.now.to_i

    schedule.redis.multi
    schedule.zrangebyscore '-inf', time
    schedule.zremrangebyscore '-inf', time
    ids = schedule.redis.exec.first

    key.redis.multi do
      ids.each { |id| queue.lpush id }
    end

    event = queue.brpoplpush(backup, 1)

    next unless event

    begin
      block.call event
    rescue Exception => e
      exceptions.rpush JSON(time: Time.now, event: event, message: e.inspect)
    ensure
      backup.del
    end
  end
end

#exceptionsObject



20
21
22
# File 'lib/later.rb', line 20

def exceptions
  @exceptions ||= key[:exceptions]
end

#keyObject



16
17
18
# File 'lib/later.rb', line 16

def key
  @key
end

#set(event, time) ⇒ Object



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

def set(event, time)
  key[:schedule].zadd time.to_i, event
end

#stopObject



40
41
42
# File 'lib/later.rb', line 40

def stop
  @stop = true
end

#unset(event) ⇒ Object



36
37
38
# File 'lib/later.rb', line 36

def unset(event)
  key[:schedule].zrem event
end