diff --git a/lib/sidetiq/clock.rb b/lib/sidetiq/clock.rb index fdaba24..5aec781 100644 --- a/lib/sidetiq/clock.rb +++ b/lib/sidetiq/clock.rb @@ -12,7 +12,7 @@ module Sidetiq START_TIME = Sidetiq.config.utc ? Time.utc(2010, 1, 1) : Time.local(2010, 1, 1) - attr_reader :schedules + attr_reader :schedules, :thread def self.method_missing(meth, *args, &block) instance.__send__(meth, *args, &block) @@ -42,6 +42,26 @@ module Sidetiq Sidetiq.config.utc ? clock_gettime.utc : clock_gettime end + def start! + return if ticking? + + Sidekiq.logger.info "Sidetiq::Clock start" + @thread = Thread.start { clock { tick } } + @thread.abort_on_exception = true + @thread.priority = Sidetiq.config.resolution + end + + def stop! + if ticking? + @thread.kill + Sidekiq.logger.info "Sidetiq::Clock stop" + end + end + + def ticking? + @thread && @thread.alive? + end + private def enqueue(worker, time) @@ -73,13 +93,6 @@ module Sidetiq end end - def start! - Sidekiq.logger.info "Sidetiq::Clock start" - thr = Thread.start { clock { tick } } - thr.abort_on_exception = true - thr.priority = Sidetiq.config.resolution - end - def clock loop do yield diff --git a/test/test_clock.rb b/test/test_clock.rb index 2bbfb0d..7754cc4 100644 --- a/test/test_clock.rb +++ b/test/test_clock.rb @@ -9,6 +9,25 @@ class TestClock < Sidetiq::TestCase Sidetiq::Clock.foo end + def test_start_stop + refute clock.ticking? + assert_nil clock.thread + + clock.start! + Thread.pass + sleep 0.01 + + assert clock.ticking? + assert_kind_of Thread, clock.thread + + clock.stop! + Thread.pass + sleep 0.01 + + refute clock.ticking? + refute clock.thread.alive? + end + def test_gettime_seconds assert_equal clock.gettime.tv_sec, Time.now.tv_sec end