Created
April 20, 2020 08:24
-
-
Save viktorchukhantsev/4d9c44a6143ae46ea7f52df607dc5c4a to your computer and use it in GitHub Desktop.
Simple jobs queue implementation on Ruby
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
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