Skip to content

Instantly share code, notes, and snippets.

@viktorchukhantsev
Created April 20, 2020 08:24
Show Gist options
  • Save viktorchukhantsev/4d9c44a6143ae46ea7f52df607dc5c4a to your computer and use it in GitHub Desktop.
Save viktorchukhantsev/4d9c44a6143ae46ea7f52df607dc5c4a to your computer and use it in GitHub Desktop.
Simple jobs queue implementation on Ruby
module MyJobs
def self.backend
@backend
end
def self.backend=(backend)
@backend = backend
end
class Processor
def self.start(concurrency = 1)
concurrency.times { |n| new("Processor #{n}") }
end
def initialize(name)
thread = Thread.new do
loop do
payload = MyJobs.backend.pop
worker_class = payload[:worker]
worker_class.new.perform(*payload[:args])
end
end
thread.name = name
end
end
module Worker
module ClassMethods
def perform_async(*args)
MyJobs.backend.push(worker: self, args: args)
end
end
end
end
MyJobs.backend = Queue.new
MyJobs::Processor.start(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment