Skip to content

Instantly share code, notes, and snippets.

@reednj
Last active March 17, 2016 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reednj/34495bcedf8e85eb8054 to your computer and use it in GitHub Desktop.
Save reednj/34495bcedf8e85eb8054 to your computer and use it in GitHub Desktop.
A ruby background work with a monitoring thread to kill the worker after a timeout
class WorkerThread
def initialize
end
def start(options = nil)
raise 'background_task needs a block' unless block_given?
options ||= {}
worker = Thread.new do
begin
yield
rescue => e
File.append 'error.log', "#{Time.now.iso8601}\t#{e.class.to_s}\t#{e.message}\n"
raise e
end
end
# if the user set a timeout then we need a thread to monitor
# the worker to make sure it doesn't run too long
if !options[:timeout].nil?
Thread.new do
sleep options[:timeout].to_f
if worker.status != false
worker.kill
File.append 'error.log', "#{Time.now.iso8601}\tbackground_task thread timeout\n"
end
end
end
worker
end
end
class File
def self.append(path, data)
File.open(path, 'a:UTF-8') do |file|
file.write data
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment