Class: Torid::Clock

Inherits:
Object
  • Object
show all
Defined in:
lib/torid/clock.rb

Overview

Internal: A source for non-duplicate microsecond timestamps.

Clock generates microsecond UNIX timestamps and guarantees that once a Clock instance is created, ‘Clock#tick` will never return the same value twice for that instance.

This is effectively a reimplementation of github.com/jamesgolick/lexical_uuid/blob/master/lib/increasing_microsecond_clock.rb combined with github.com/jamesgolick/lexical_uuid/blob/master/lib/time_ext.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prev_stamp = Clock.stamp, mutex = Mutex.new) ⇒ Clock

Internal: Create a new Clock

prev_stamp - An initial value for the previous timestamp (default:

Clock.stamp)

mutex - The synchronizing object to use



33
34
35
36
# File 'lib/torid/clock.rb', line 33

def initialize( prev_stamp = Clock.stamp, mutex = Mutex.new )
  @prev_stamp = prev_stamp
  @mutex      = mutex
end

Class Method Details

.stampObject

Internal: Return the current microsecond UNIX timstamp

Example:

Clock.stamp => 1404774462369341

Returns an Integer



23
24
25
26
# File 'lib/torid/clock.rb', line 23

def self.stamp
  now = Time.now
  (now.to_f * 1_000_000).floor
end

.tickObject

Internal: Return the next ‘#tick` of the default Clock.



61
62
63
# File 'lib/torid/clock.rb', line 61

def self.tick
  @instance.tick
end

Instance Method Details

#tickObject

Internal: Return the next tick of the clock.

Return the next tick of the clock, which will be a Clock.stamp value. This method will continue to return ever increasing values from when it was created.

Returns an Integer.



45
46
47
48
49
50
51
52
53
54
# File 'lib/torid/clock.rb', line 45

def tick
  @mutex.synchronize do
    new_stamp   = Clock.stamp
    @prev_stamp = if new_stamp > @prev_stamp then
      new_stamp
    else
      @prev_stamp + 1
    end
  end
end