Class: Stoatrb::RequestQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/stoatrb/request_queue.rb

Instance Method Summary collapse

Constructor Details

#initialize(delay_between_requests_ms = 100) ⇒ RequestQueue

Returns a new instance of RequestQueue.



7
8
9
10
11
12
13
14
15
# File 'lib/stoatrb/request_queue.rb', line 7

def initialize(delay_between_requests_ms = 100)
	@queue = []
	@mutex = Mutex.new
	@condition = ConditionVariable.new
	@processing_thread = nil
	@running = false
	@delay_between_requests = delay_between_requests_ms / 1000.0
	@logger = Stoatrb::DebugLogger.new
end

Instance Method Details

#enqueue(&block) ⇒ Object



17
18
19
20
21
22
# File 'lib/stoatrb/request_queue.rb', line 17

def enqueue(&block)
	@mutex.synchronize do
		@queue << block
		@condition.signal
	end
end

#start_processingObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/stoatrb/request_queue.rb', line 24

def start_processing
	return if @running

	@running = true
	@processing_thread = Thread.new do
		@logger.debug "RequestQueue processing thread started."
		while @running
			request = nil
			@mutex.synchronize do
				@condition.wait(@mutex) if @queue.empty?
				request = @queue.shift unless @queue.empty?
			end

			if request
				begin
					request.call
					sleep @delay_between_requests
				rescue => e
					@logger.debug "AN ERROR HAS OCCURED: Error processing queued request: #{e.message}"
					@logger.debug e.backtrace.join("\n")
				end
			end
		end
		@logger.debug "RequestQueue processing thread stopped."
	end
end

#stop_processingObject



51
52
53
54
55
56
57
# File 'lib/stoatrb/request_queue.rb', line 51

def stop_processing
	@running = false
	@mutex.synchronize do
		@condition.signal
	end
	@processing_thread.join if @processing_thread&.alive?
end