Class: Shoryuken::Helpers::TimerTask
- Inherits:
-
Object
- Object
- Shoryuken::Helpers::TimerTask
- 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
-
#execute ⇒ TimerTask
Starts the timer task execution.
-
#initialize(execution_interval:, &task) { ... } ⇒ TimerTask
constructor
Initializes a new TimerTask.
-
#kill ⇒ Boolean
Stops and kills the timer task.
Constructor Details
#initialize(execution_interval:, &task) { ... } ⇒ TimerTask
Initializes a new TimerTask
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
#execute ⇒ TimerTask
Starts the timer task execution
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 |
#kill ⇒ Boolean
Stops and kills the timer task
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/shoryuken/helpers/timer_task.rb', line 44 def kill thread_to_kill = nil @mutex.synchronize do return false if @killed @killed = true @running = false thread_to_kill = @thread end # Kill the thread AFTER releasing the mutex. The timer loop's ensure # block calls @mutex.synchronize to clear @running; killing the thread # while holding that mutex deadlocks on Ruby 3.2, where Thread#kill # yields the GVL to the killed thread for cleanup before returning. thread_to_kill&.kill if thread_to_kill&.alive? true end |