diff --git a/lib/sidetiq.rb b/lib/sidetiq.rb index 18c7be8..40178e7 100644 --- a/lib/sidetiq.rb +++ b/lib/sidetiq.rb @@ -1,11 +1,11 @@ # stdlib -require 'singleton' require 'monitor' require 'ostruct' +require 'singleton' # gems -require 'sidekiq' require 'ice_cube' +require 'sidekiq' # c extensions require 'sidetiq_ext' @@ -13,6 +13,7 @@ require 'sidetiq_ext' # internal require 'sidetiq/config' require 'sidetiq/clock' +require 'sidetiq/middleware' require 'sidetiq/schedule' require 'sidetiq/schedulable' require 'sidetiq/version' diff --git a/lib/sidetiq/middleware.rb b/lib/sidetiq/middleware.rb new file mode 100644 index 0000000..0db7251 --- /dev/null +++ b/lib/sidetiq/middleware.rb @@ -0,0 +1,20 @@ +module Sidetiq + class Middleware + def initialize + @clock = Sidetiq::Clock.instance + end + + def call(*args) + # Restart the clock if the thread died. + @clock.start! if !@clock.ticking? + yield + end + end +end + +Sidekiq.configure_server do |config| + config.server_middleware do |chain| + chain.add Sidetiq::Middleware + end +end + diff --git a/test/test_middleware.rb b/test/test_middleware.rb new file mode 100644 index 0000000..12a5b91 --- /dev/null +++ b/test/test_middleware.rb @@ -0,0 +1,18 @@ +require_relative 'helper' + +class TestMiddleware < Sidetiq::TestCase + def middleware + Sidetiq::Middleware.new + end + + def test_restarts_clock + clock.stubs(:ticking?).returns(false) + clock.expects(:start!).once + middleware.call {} + + clock.stubs(:ticking?).returns(true) + clock.expects(:start!).never + middleware.call {} + end +end +