-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5edffaa
commit 42b74f7
Showing
1 changed file
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# frozen_string_literal: true | ||
|
||
module Datadog | ||
module Core | ||
module Remote | ||
class Worker | ||
def initialize(interval:, &block) | ||
@mutex = Mutex.new | ||
@thr = nil | ||
|
||
@starting = false | ||
@stopping = false | ||
@started = false | ||
|
||
@interval = interval | ||
@block = block | ||
end | ||
|
||
def start | ||
Datadog.logger.debug { 'remote worker starting' } | ||
|
||
@mutex.lock | ||
|
||
return if @starting || @started | ||
|
||
@starting = true | ||
|
||
@thr = Thread.new { poll(@interval) } | ||
|
||
@started = true | ||
@starting = false | ||
|
||
Datadog.logger.debug { 'remote worker started' } | ||
ensure | ||
@mutex.unlock | ||
end | ||
|
||
def stop | ||
Datadog.logger.debug { 'remote worker stopping' } | ||
|
||
@mutex.lock | ||
|
||
@stopping = true | ||
|
||
@thr.kill unless @thr.nil? | ||
|
||
@started = false | ||
@stopping = false | ||
|
||
Datadog.logger.debug { 'remote worker stopped' } | ||
ensure | ||
@mutex.unlock | ||
end | ||
|
||
def started? | ||
@started | ||
end | ||
|
||
private | ||
|
||
def poll(interval) | ||
loop do | ||
break unless @mutex.synchronize { @starting || @started } | ||
|
||
call | ||
|
||
sleep(interval) | ||
end | ||
end | ||
|
||
def call | ||
Datadog.logger.debug { 'remote worker perform' } | ||
|
||
@block.call | ||
end | ||
end | ||
end | ||
end | ||
end |