Sha256: 6b96f426f9f8d4f568ae0cb9f3206a18bca598694322a6541c5352a9bd663c83
Contents?: true
Size: 1.01 KB
Versions: 4
Compression:
Stored size: 1.01 KB
Contents
require 'thread' module Attention # Periodic asynchronous code execution class Timer attr_reader :frequency # @!visibility private attr_reader :callback, :lock, :thread # Creates and {#start}s the timer # @param frequency [Numeric] How often to execute # @yield The code to be executed def initialize(frequency, &callback) @frequency = frequency @callback = callback @lock = Mutex.new start end # Starts the timer def start @thread ||= Thread.new do loop do sleep @frequency lock.synchronize do callback.call end end end end # @return [Boolean] True if the timer is started def started? !!thread end # Stops the timer if it's started def stop return if stopped? lock.synchronize do thread.kill @thread = nil end end # @return [Boolean] True if the timer is stopped def stopped? !started? end end end
Version data entries
4 entries across 4 versions & 1 rubygems
Version | Path |
---|---|
attention-0.0.5 | lib/attention/timer.rb |
attention-0.0.4 | lib/attention/timer.rb |
attention-0.0.3 | lib/attention/timer.rb |
attention-0.0.2 | lib/attention/timer.rb |