Class: Shoryuken::Helpers::TimerTask

Inherits:
Object
  • Object
show all
Defined in:
lib/shoryuken/helpers/timer_task.rb

Overview

A thread-safe timer task implementation. Drop-in replacement for Concurrent::TimerTask without external dependencies.

Instance Method Summary collapse

Constructor Details

#initialize(execution_interval:, &task) ⇒ TimerTask

Returns a new instance of TimerTask.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/shoryuken/helpers/timer_task.rb', line 8

def initialize(execution_interval:, &task)
  raise ArgumentError, 'A block must be provided' unless block_given?

  @execution_interval = Float(execution_interval)
  raise ArgumentError, 'execution_interval must be positive' if @execution_interval <= 0

  @task = task
  @mutex = Mutex.new
  @thread = nil
  @running = false
  @killed = false
end

Instance Method Details

#executeObject

Start the timer task execution



22
23
24
25
26
27
28
29
30
# File 'lib/shoryuken/helpers/timer_task.rb', line 22

def execute
  @mutex.synchronize do
    return self if @running || @killed

    @running = true
    @thread = Thread.new { run_timer_loop }
  end
  self
end

#killObject

Stop and kill the timer task



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/shoryuken/helpers/timer_task.rb', line 33

def kill
  @mutex.synchronize do
    return false if @killed

    @killed = true
    @running = false

    @thread.kill if @thread&.alive?
  end
  true
end