Skip to content

Commit 9716bb3

Browse files
Change cleanup checks
1 parent 4c96092 commit 9716bb3

File tree

3 files changed

+14
-9
lines changed

3 files changed

+14
-9
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ The package can be installed by adding `uuid_v7` to your list of dependencies in
3838
```elixir
3939
def deps do
4040
[
41-
{:uuid_v7, "~> 0.4.3"}
41+
{:uuid_v7, "~> 0.4.4"}
4242
]
4343
end
4444
```

lib/clock.ex

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ defmodule UUIDv7.Clock do
7777
state = %{
7878
table: :ets.new(__MODULE__, ets_opts),
7979
interval_ms: interval_ms,
80+
timestamp_ref: :persistent_term.get(__MODULE__),
8081
cleanup_tick_cutoff: cleanup_tick_cutoff
8182
}
8283

@@ -87,7 +88,7 @@ defmodule UUIDv7.Clock do
8788

8889
@impl GenServer
8990
def handle_info(:cleanup, state) do
90-
cleanup(state.cleanup_tick_cutoff)
91+
cleanup(state.timestamp_ref, state.cleanup_tick_cutoff)
9192
schedule_cleanup(state.interval_ms)
9293
{:noreply, state}
9394
end
@@ -106,12 +107,16 @@ defmodule UUIDv7.Clock do
106107
:ets.update_counter(__MODULE__, ts, 1, {ts, seed})
107108
end
108109

109-
# NOTE: The thing that bothers me the most about this implementation is the
110-
# cleanup and how it may (possibly?) effect performance. I need to do some
111-
# benchmarks to test if this effects `:ets.update_counter/4` at all.
112-
defp cleanup(cutoff) do
113-
timestamp = System.system_time(:millisecond) - cutoff
114-
:ets.select_delete(__MODULE__, [{{:"$1", :_}, [{:<, :"$1", timestamp}], [true]}])
110+
# NOTE: I still want to benchmark different cutoffs and cleanup intervals.
111+
defp cleanup(timestamp_ref, cutoff) do
112+
timestamp = System.system_time(:millisecond)
113+
previous_ts = :atomics.get(timestamp_ref, 1)
114+
115+
# If the last timestamp was over 10 seconds ago, then we don't bother to run the cleanup.
116+
if timestamp - previous_ts < 10_000 do
117+
# Cleanup all entries that are older than the cutoff.
118+
:ets.select_delete(__MODULE__, [{{:"$1", :_}, [{:<, :"$1", timestamp - cutoff}], [true]}])
119+
end
115120
end
116121

117122
defp schedule_cleanup(interval_ms) do

mix.exs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
defmodule UUIDv7.MixProject do
22
use Mix.Project
33

4-
@version "0.4.3"
4+
@version "0.4.4"
55

66
@repo_url "https://github.com/ryanwinchester/uuidv7"
77

0 commit comments

Comments
 (0)