File: tick.rb

package info (click to toggle)
ruby-concurrent 1.1.6%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 30,284 kB
  • sloc: ruby: 30,875; java: 6,117; javascript: 1,114; ansic: 288; makefile: 10; sh: 6
file content (57 lines) | stat: -rw-r--r-- 1,317 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'concurrent/synchronization'
require 'concurrent/utility/monotonic_time'

module Concurrent
  class Channel

    # A convenience class representing a single moment in monotonic time.
    # Returned by {Concurrent::Channel} tickers and timers when they
    # resolve.
    #
    # Includes `Comparable` and can be compared to monotonic_time, UTC
    # time, or epoch time.
    #
    # @see Concurrent.monotonic_time
    # @see Concurrent::Channel.ticker
    # @see Concurrent::Channel.timer
    class Tick < Synchronization::Object
      include Comparable
      safe_initialization!

      STRING_FORMAT = '%F %T.%6N %z %Z'.freeze

      attr_reader :monotonic, :utc

      def initialize(tick = Concurrent.monotonic_time)
        @monotonic = tick
        @utc = monotonic_to_utc(tick).freeze
      end

      def epoch
        @utc.to_f
      end

      def to_s
        @utc.strftime(STRING_FORMAT)
      end

      def <=>(other)
        if other.is_a? Numeric
          @monotonic <=> other
        elsif other.is_a? Time
          @utc <=> other.utc
        elsif other.is_a? Tick
          @monotonic <=> other.monotonic
        else
          nil
        end
      end

      private

      def monotonic_to_utc(tick)
        Time.now.utc + Concurrent.monotonic_time - tick
      end
    end
  end
end