Class: Async::Timer

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

Defined Under Namespace

Classes: AlreadyStarted, Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delay = nil, repeat: true, start: true, run_on_start: false, call: nil, on_error: nil, parent: Async::Task.current, &block) ⇒ Timer

rubocop:disable Metrics/CyclomaticComplexity,Metrics/ParameterLists

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/async/timer.rb', line 10

def initialize(delay = nil, # rubocop:disable Metrics/CyclomaticComplexity,Metrics/ParameterLists
               repeat: true,
               start: true,
               run_on_start: false,
               call: nil,
               on_error: nil,
               parent: Async::Task.current, &block)
  callables = [call, block]
  raise ArgumentError, "either block or call: must be given" if callables.all?(&:nil?) || callables.none?(&:nil?)

  @delay = delay
  @repeat = repeat
  @run_on_start = run_on_start
  @callable = call || block
  @on_error = on_error || ->(e) { raise e }
  @parent = parent

  self.start if start
end

Instance Attribute Details

#dealayObject (readonly)

Returns the value of attribute dealay.



4
5
6
# File 'lib/async/timer.rb', line 4

def dealay
  @dealay
end

#repeatObject (readonly)

Returns the value of attribute repeat.



4
5
6
# File 'lib/async/timer.rb', line 4

def repeat
  @repeat
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


33
# File 'lib/async/timer.rb', line 33

def active? = @active

#callObject



31
# File 'lib/async/timer.rb', line 31

def call = @callable.call

#rescued_callObject



60
61
62
63
64
# File 'lib/async/timer.rb', line 60

def rescued_call
  call
rescue StandardError => e
  @on_error.call(e)
end

#restart(delay = @delay, run: false) ⇒ Object



35
36
37
38
# File 'lib/async/timer.rb', line 35

def restart(delay = @delay, run: false)
  stop
  start(delay, run:)
end

#start(delay = @delay, run: false) ⇒ Object

Raises:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/async/timer.rb', line 40

def start(delay = @delay, run: false)
  raise AlreadyStarted, "Timer already started" if active?
  raise ArgumentError, "delay cannot be nil" if delay.nil?

  @delay = delay
  @active = true

  @task = @parent.async do
    rescued_call if @run_on_start || run

    loop do
      sleep(@delay)
      rescued_call
      break unless @repeat
    ensure
      @active = false
    end
  end
end

#stopObject



30
# File 'lib/async/timer.rb', line 30

def stop = @task.stop(true)