Created
January 26, 2020 18:12
-
-
Save sailor/29d163fd45bba55185f47c6e613722a0 to your computer and use it in GitHub Desktop.
PoC of a background job system in ruby that work asynchronously (using event loops)
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
require 'bundler/inline' | |
require 'json' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'async-redis' | |
end | |
endpoint = Async::Redis.local_endpoint | |
redis = Async::Redis::Client.new(endpoint) | |
QUEUE = 'queue:default' | |
module Quiq | |
def self.included(base) | |
base.class_eval do | |
attr_accessor :task | |
end | |
end | |
end | |
class JobWrapper | |
def initialize(item) | |
@item = JSON.parse(item) rescue nil | |
end | |
def run | |
return if @item.nil? | |
Async do |task| | |
klass = Object.const_get(@item['wrapped']) | |
klass.include(Quiq) | |
args = @item['args'].first['arguments'] | |
job = klass.new | |
job.task = task | |
job.perform(*args) | |
end | |
end | |
end | |
class TestJob | |
def perform(data, wait) | |
puts "Receiving new data: #{data}" | |
task.sleep wait | |
puts "Time to wake up after #{wait} seconds" | |
end | |
end | |
Async do | |
loop do | |
data = redis.brpop(QUEUE) | |
JobWrapper.new(data.last).run | |
end | |
ensure | |
redis.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment