Expose the time remaining in HHWheelTimer::Callback
authorJody Ho <jodyho@fb.com>
Thu, 16 Nov 2017 07:23:02 +0000 (23:23 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 16 Nov 2017 07:45:06 +0000 (23:45 -0800)
Summary:
We would like to know the time remaining for a scheduled timeout to decide
whether a new event should override the scheduled timeout.

Reviewed By: yfeldblum

Differential Revision: D6334067

fbshipit-source-id: f172d5cd7fc804db5fd53a42d06cadfddf857e22

folly/io/async/HHWheelTimer.h
folly/io/async/test/HHWheelTimerTest.cpp

index a8978a1b53520385ba15093bde47322a3bb31acf..5544c2d661b8ecc2305e893b0ab5a32950257593 100644 (file)
@@ -104,6 +104,15 @@ class HHWheelTimer : private folly::AsyncTimeout,
       return wheel_ != nullptr;
     }
 
+    /**
+     * Get the time remaining until this timeout expires. Return 0 if this
+     * timeout is not scheduled or expired. Otherwise, return expiration time
+     * minus getCurTime().
+     */
+    std::chrono::milliseconds getTimeRemaining() {
+      return getTimeRemaining(getCurTime());
+    }
+
    protected:
     /**
      * Don't override this unless you're doing a test. This is mainly here so
index a05bb6985ed603e301ea285a3113dec7fa78848d..f7744608df0b0cdc7a65e1cb85effcfb1aba19d4 100644 (file)
@@ -430,3 +430,27 @@ TEST_F(HHWheelTimerTest, IntrusivePtr) {
   T_CHECK_TIMEOUT(start, t3.timestamps[0], milliseconds(10));
   T_CHECK_TIMEOUT(start, end, milliseconds(10));
 }
+
+TEST_F(HHWheelTimerTest, GetTimeRemaining) {
+  StackWheelTimer t(&eventBase, milliseconds(1));
+  TestTimeout t1;
+
+  // Not scheduled yet, time remaining should be zero
+  ASSERT_EQ(t1.getTimeRemaining(), milliseconds(0));
+  ASSERT_EQ(t.count(), 0);
+
+  // Scheduled, time remaining should be less than or equal to the scheduled
+  // timeout
+  t.scheduleTimeout(&t1, milliseconds(10));
+  ASSERT_LE(t1.getTimeRemaining(), milliseconds(10));
+
+  TimePoint start;
+  eventBase.loop();
+  TimePoint end;
+
+  // Expired and time remaining should be zero
+  ASSERT_EQ(t1.getTimeRemaining(), milliseconds(0));
+
+  ASSERT_EQ(t.count(), 0);
+  T_CHECK_TIMEOUT(start, end, milliseconds(10));
+}