Skip to content

Instantly share code, notes, and snippets.

@fred
Created June 28, 2013 17:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fred/5886368 to your computer and use it in GitHub Desktop.
Save fred/5886368 to your computer and use it in GitHub Desktop.
Running clockwork inside a Sidekiq Thread using Celluloid
###
### Rails.root/lib/scheduler.rb
###
require 'celluloid/autostart'
module AwesomeRailsApp
class ClockworkScheduler
include Celluloid
include Clockwork
def run
# I'd wait 20 seconds for workers to boot completely and process pending jobs
sleep 20
Sidekiq.logger.info "Starting Clockwork Thread Fiber"
Clockwork::run
rescue => ex
return if ex.is_a?(Celluloid::Task::TerminatedError)
Sidekiq.logger.info "ClockworkScheduler Thread failed! - "+ex.message+"\n"+ex.backtrace.join("\n")
end
end
end
###
### Rails.root/config/initializers/sidekiq.rb
###
require './lib/clock'
require './lib/scheduler'
# Connecting to Redis vias Socket is 10-20% faster than TCP
if ENV["REDISTOGO_URL"]
url = ENV["REDISTOGO_URL"]
elsif File.exist? '/usr/local/var/run/redis.sock'
url = 'unix:/usr/local/var/run/redis.sock'
elsif File.exist? '/var/run/redis/redis.sock'
url = 'unix:/var/run/redis/redis.sock'
else
url = 'redis://127.0.0.1:6379'
end
Sidekiq.configure_server do |config|
config.redis = { namespace: 'mynamespace', url: url }
AwesomeRailsApp::ClockworkScheduler.new.run!
end
Sidekiq.configure_client do |config|
config.redis = { namespace: 'mynamespace', size: 10, url: url }
end
###
### Rails.root/lib/clock.rb
###
require 'clockwork'
module Clockwork
every 1.minute, "sample_worker" do
Sidekiq.logger.info "Starting KickAssWorker"
KickAssWorker.perform_async('something')
end
# every 1.day, 'my_worker.late_night_work', :at => '4:30 am' do
# MyWorker.late_night_work
# end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment