Class: Torid::Clock
- Inherits:
-
Object
- Object
- Torid::Clock
- 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
Instance Attribute Summary collapse
-
#prev_stamp ⇒ Object
readonly
Returns the value of attribute prev_stamp.
Class Method Summary collapse
-
.stamp ⇒ Object
Internal: Return the current microsecond UNIX timstamp.
-
.tick ⇒ Object
Internal: Return the next ‘#tick` of the default Clock.
Instance Method Summary collapse
-
#initialize(prev_stamp = Clock.stamp, mutex = Mutex.new) ⇒ Clock
constructor
Internal: Create a new Clock.
-
#tick ⇒ Object
Internal: Return the next tick of the clock.
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
39 40 41 42 |
# File 'lib/torid/clock.rb', line 39 def initialize( prev_stamp = Clock.stamp, mutex = Mutex.new ) @prev_stamp = prev_stamp @mutex = mutex end |
Instance Attribute Details
#prev_stamp ⇒ Object (readonly)
Returns the value of attribute prev_stamp.
32 33 34 |
# File 'lib/torid/clock.rb', line 32 def prev_stamp @prev_stamp end |
Class Method Details
.stamp ⇒ Object
Internal: 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 an Integer
27 28 29 30 |
# File 'lib/torid/clock.rb', line 27 def self.stamp now = Time.now (now.to_f * 1_000_000).floor end |
.tick ⇒ Object
Internal: Return the next ‘#tick` of the default Clock.
67 68 69 |
# File 'lib/torid/clock.rb', line 67 def self.tick @instance.tick end |
Instance Method Details
#tick ⇒ Object
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.
51 52 53 54 55 56 57 58 59 60 |
# 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 |