Skip to content

Commit

Permalink
Use nanoTime instead of currentTimeMillis for elapsed time
Browse files Browse the repository at this point in the history
System/currentTimeMillis is not guaranteed to progress monotonically.
NTP shifts, leap seconds, and manual system time changes can all cause
elapsed time calculations to be incorrect if you use
currentTimeMillis.

nanoTime is always calculated against a fixed point and proceeds
monotonically.

https://go.googlesource.com/proposal/+/master/design/12914-monotonic.md
has a good discussion on monotonic time.
  • Loading branch information
danielcompton authored and boxxxie committed Apr 13, 2022
1 parent c65bbfb commit 083e412
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/durable_queue.clj
Original file line number Diff line number Diff line change
Expand Up @@ -567,10 +567,10 @@
(while (.get ref)
(when-let [q (.get ref)]
(try
(let [start (System/currentTimeMillis)]
(let [start (System/nanoTime)]
(fsync q)
(let [end (System/currentTimeMillis)]
(Thread/sleep (max 0 (- fsync-interval (- end start))))))
(let [end (System/nanoTime)]
(Thread/sleep (max 0 (- (* 1000000 fsync-interval) (- end start))))))
(catch Throwable e
)))))))

Expand Down Expand Up @@ -765,16 +765,16 @@
"Returns a lazy sequence of tasks that can be consumed in `interval` milliseconds. This will
terminate after that time has elapsed, even if there are still tasks immediately available."
[qs q-name interval]
(let [now (System/currentTimeMillis)]
(let [now (System/nanoTime)]
(lazy-seq
(let [now' (System/currentTimeMillis)
remaining (- interval (- now' now))]
(let [now' (System/nanoTime)
remaining (- (* 1000000 interval) (- now' now))]
(when (pos? remaining)
(let [task (take! qs q-name remaining ::none)]
(when-not (= ::none task)
(cons
task
(interval-task-seq qs q-name (- interval (- (System/currentTimeMillis) now)))))))))))
(interval-task-seq qs q-name (- (* 1000000 interval) (- (System/nanoTime) now)))))))))))

(defn complete!
"Marks a task as complete."
Expand Down

0 comments on commit 083e412

Please sign in to comment.