From f7a334a979c87ea8fbf564382b270ec8a2517ea6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Simon=20D=C3=A9saulniers?= <sim.desaulniers@gmail.com>
Date: Thu, 21 Apr 2016 00:46:32 -0400
Subject: [PATCH] dht: make sure searchStep is called when needed.

---
 include/opendht/scheduler.h | 14 +++++++++++---
 src/dht.cpp                 |  3 +++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/include/opendht/scheduler.h b/include/opendht/scheduler.h
index 6959cb34..a79ad1e6 100644
--- a/include/opendht/scheduler.h
+++ b/include/opendht/scheduler.h
@@ -39,6 +39,7 @@ public:
     struct Job {
         bool done;
         bool cancelled;
+		time_point time;
         std::function<void()> do_;
     };
 
@@ -51,8 +52,10 @@ public:
      * @return pointer to the newly scheduled job.
      */
     std::shared_ptr<Scheduler::Job> add(time_point time, std::function<void()> job_func) {
-        auto job = std::make_shared<Job>(Job {false, false, std::move(job_func)});
-        timers.emplace(std::move(time), job);
+		auto scheduled_time = std::max(time, now); /* This should prevent running an auto rescheduling job forever
+													  before the Scheduler::run method ends. */
+        auto job = std::make_shared<Job>(Job {false, false, scheduled_time, std::move(job_func)});
+        timers.emplace(std::move(scheduled_time), job);
         return job;
     }
 
@@ -80,7 +83,12 @@ public:
         syncTime();
         while (not timers.empty()) {
             auto timer = timers.begin();
-            if (timer->first > now)
+			/*
+			 * Running jobs scheduled before "now" prevents run+rescheduling
+			 * loops before this method ends. It is garanteed by the fact that a
+			 * job will at least be scheduled for "now" and not before.
+			 */
+			if (not (timer->first < now))
                 break;
 
             auto& job = timer->second;
diff --git a/src/dht.cpp b/src/dht.cpp
index 98197f71..5df3bc3a 100644
--- a/src/dht.cpp
+++ b/src/dht.cpp
@@ -970,6 +970,9 @@ Dht::searchStep(std::shared_ptr<Search> sr)
             }
         }
     }
+
+    /* periodic searchStep scheduling. */
+    sr->nextSearchStep = scheduler.edit(sr->nextSearchStep, sr->getNextStepTime(types, now));
 }
 
 
-- 
GitLab