Module: Spikard::Background
- Defined in:
- lib/spikard/background.rb
Overview
Background job helpers.
Constant Summary collapse
- SHUTDOWN =
Object.new
Class Method Summary collapse
- .ensure_worker ⇒ Object
-
.run(&block) ⇒ Object
Schedule a block to run after the response has been returned.
-
.shutdown ⇒ Object
Stop the background worker thread to allow process shutdown.
Class Method Details
.ensure_worker ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/spikard/background.rb', line 13 def ensure_worker return if @worker&.alive? @worker_mutex.synchronize do return if @worker&.alive? @worker = Thread.new do loop do job = @queue.pop break if job.equal?(SHUTDOWN) begin job.call rescue StandardError => e warn("[spikard.background] job failed: #{e.}") end end end end end |
.run(&block) ⇒ Object
Schedule a block to run after the response has been returned.
35 36 37 38 39 40 |
# File 'lib/spikard/background.rb', line 35 def run(&block) raise ArgumentError, 'background.run requires a block' unless block ensure_worker @queue << block end |
.shutdown ⇒ Object
Stop the background worker thread to allow process shutdown.
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/spikard/background.rb', line 43 def shutdown @worker_mutex.synchronize do return unless @worker&.alive? @queue << SHUTDOWN @worker.join(1) @worker.kill if @worker.alive? @worker = nil end end |