View Source Sonyflakex.Time (Sonyflakex v0.2.0)

Helpers to handle timestamp calculations.

Summary

Types

Timestamp in 10ms unit used in Sonyflake IDs.

UNIX timestamp in ms.

Functions

Computes timestamp in unit of 10ms elapsed from start time.

Default timestamp used as start reference when computing elapsed time.

Computed how many milliseconds to wait from current time until the next timestamp window from elapsed_time.

Converts DateTime to timestamp in unit of 10ms.

Types

@type sonyflake_timestamp() :: non_neg_integer()

Timestamp in 10ms unit used in Sonyflake IDs.

@type unix_timestamp_ms() :: non_neg_integer()

UNIX timestamp in ms.

Functions

Link to this function

current_elapsed_time(start_time, utc_now \\ &DateTime.utc_now/0)

View Source
@spec current_elapsed_time(sonyflake_timestamp(), (-> DateTime.t())) ::
  sonyflake_timestamp()

Computes timestamp in unit of 10ms elapsed from start time.

Args:

  • start_time: Timestamp in unit of 10 ms used as reference.
  • utc_now: (Optional) Function that returns current DateTime using the same contract as DateTime.utc_now/0. It is used to mock datetime generation in tests.
@spec default_epoch() :: sonyflake_timestamp()

Default timestamp used as start reference when computing elapsed time.

Examples

iex> Sonyflakex.Time.default_epoch()
140952960000
Link to this function

time_until_next_timestamp(start_time, elapsed_time, current_time)

View Source
@spec time_until_next_timestamp(
  sonyflake_timestamp(),
  sonyflake_timestamp(),
  unix_timestamp_ms()
) :: non_neg_integer()

Computed how many milliseconds to wait from current time until the next timestamp window from elapsed_time.

It is used to pause the process and wait until the next timestamp windows to generate new IDs and avoid a sequence overflow.

Args:

  • start_time: Timestamp in unit of 10ms used as base reference for timestamps.
  • elapsed_time: Timestamp in unit of 10ms to generate the next ID.
  • current_time: Current clock timestamp in ms.

Returns: time in milliseconds until next elapsed time or zero if next elapsed time is in the past.

Examples

iex> Sonyflakex.Time.time_until_next_timestamp(0, 1, 15)
5
Link to this function

to_sonyflake_time(datetime)

View Source
@spec to_sonyflake_time(DateTime.t()) :: sonyflake_timestamp()

Converts DateTime to timestamp in unit of 10ms.

Examples

iex> Sonyflakex.Time.to_sonyflake_time(~U[2020-10-01 00:00:01.020777Z])
160151040102