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

Initializes a new TimerTask

Parameters:

  • execution_interval (Float)

    interval in seconds between task executions

  • task (Proc)

    the task to execute on each interval (provided as a block)

Yields:

  • the task to execute on each interval

Raises:

  • (ArgumentError)

    if no block is provided or interval is not positive



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/shoryuken/helpers/timer_task.rb', line 15

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

#executeTimerTask

Starts the timer task execution

Returns:



31
32
33
34
35
36
37
38
39
# File 'lib/shoryuken/helpers/timer_task.rb', line 31

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

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

#killBoolean

Stops and kills the timer task

Returns:

  • (Boolean)

    true if killed, false if already killed



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/shoryuken/helpers/timer_task.rb', line 44

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

    @killed = true
    @running = false

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