Skip to content

Instantly share code, notes, and snippets.

@khalilgharbaoui
Forked from dwkoogt/delay_worker.rb
Created October 23, 2018 00:36
Show Gist options
  • Save khalilgharbaoui/a35d03de4cce5c25fd5bd58663bb6210 to your computer and use it in GitHub Desktop.
Save khalilgharbaoui/a35d03de4cce5c25fd5bd58663bb6210 to your computer and use it in GitHub Desktop.
Delay worker with delay handler and Rails adapter for Sneakers
#
# enqueue with following parameters hash:
# - headers
# - work_at - time of execution
# - work_queue - destination queue for actually doing the work
#
class DelayWorker
include Sneakers::Worker
from_queue :treadmill, { handler: Sneakers::Handlers::Delay }
def work(msg)
# let the handler do all the work
reject!
end
end
require 'sneakers'
require 'thread'
module ActiveJob
module QueueAdapters
# == Sneakers adapter for Active Job
#
# A high-performance RabbitMQ background processing framework for Ruby.
# Sneakers is being used in production for both I/O and CPU intensive
# workloads, and have achieved the goals of high-performance and
# 0-maintenance, as designed.
#
# Read more about Sneakers {here}[https://github.com/jondot/sneakers].
#
# To use Sneakers set the queue_adapter config to +:sneakers+.
#
# Rails.application.config.active_job.queue_adapter = :sneakers
class SneakersAdapter
@monitor = Monitor.new
class << self
def enqueue(job) #:nodoc:
@monitor.synchronize do
JobWrapper.from_queue job.queue_name
JobWrapper.enqueue ActiveSupport::JSON.encode(job.serialize)
end
end
def enqueue_at(job, timestamp) #:nodoc:
@monitor.synchronize do
JobWrapper.from_queue :treadmill
JobWrapper.enqueue ActiveSupport::JSON.encode(job.serialize), headers: { work_at: timestamp, work_queue: job.queue_name }
end
end
end
class JobWrapper #:nodoc:
include Sneakers::Worker
from_queue 'default'
def work(msg)
job_data = ActiveSupport::JSON.decode(msg)
Base.execute job_data
ack!
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment