class Torid::Clock

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

Attributes

prev_stamp[R]

Internal

↑ top

Public Class Methods

new( prev_stamp = Clock.stamp, mutex = Mutex.new ) click to toggle source

Create a new Clock

prev_stamp

An initial value for the previous timestamp (default: Clock.stamp)

mutex

The synchronizing object to use

# File lib/torid/clock.rb, line 39
def initialize( prev_stamp = Clock.stamp, mutex = Mutex.new )
  @prev_stamp = prev_stamp
  @mutex      = mutex
end
stamp() click to toggle source

Return the current microsecond UNIX timstamp

Since this value is outside of any mutex, it is not valid to comopare it against any value from 'tick'. This is a utility method for use soley inside of the Clock instance.

Example:

Clock.stamp => 1404774462369341

Returns

Returns an Integer

# File lib/torid/clock.rb, line 27
def self.stamp
  now = Time.now
  (now.to_f * 1_000_000).floor
end
tick() click to toggle source

Return the next `#tick` of the default Clock.

# File lib/torid/clock.rb, line 67
def self.tick
  @instance.tick
end

Public Instance Methods

tick() click to toggle source

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

Returns an Integer.

# File lib/torid/clock.rb, line 51
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