Skip to content

Instantly share code, notes, and snippets.

@sailor
Created January 26, 2020 18:12
Show Gist options
  • Save sailor/29d163fd45bba55185f47c6e613722a0 to your computer and use it in GitHub Desktop.
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)
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