Browse Source

Replace timer facility with chrono lib

Tatsuhiro Tsujikawa 10 năm trước cách đây
mục cha
commit
99cd73c092
100 tập tin đã thay đổi với 418 bổ sung392 xóa
  1. 7 5
      src/AbstractCommand.cc
  2. 4 4
      src/AbstractCommand.h
  3. 2 1
      src/AbstractHttpServerResponseCommand.cc
  4. 1 1
      src/AbstractProxyRequestCommand.cc
  5. 2 2
      src/ActivePeerConnectionCommand.cc
  6. 2 2
      src/ActivePeerConnectionCommand.h
  7. 9 4
      src/AdaptiveURISelector.cc
  8. 1 2
      src/AdaptiveURISelector.h
  9. 3 3
      src/AutoSaveCommand.cc
  10. 2 1
      src/AutoSaveCommand.h
  11. 2 1
      src/BackupIPv4ConnectCommand.cc
  12. 1 1
      src/BackupIPv4ConnectCommand.h
  13. 2 0
      src/BtAnnounce.cc
  14. 2 2
      src/BtAnnounce.h
  15. 10 7
      src/BtLeecherStateChoke.cc
  16. 5 1
      src/BtSeederStateChoke.cc
  17. 0 1
      src/BtSeederStateChoke.h
  18. 7 6
      src/BtSetup.cc
  19. 4 4
      src/BtStopDownloadCommand.cc
  20. 2 2
      src/BtStopDownloadCommand.h
  21. 1 1
      src/ConnectCommand.cc
  22. 6 5
      src/ConsoleStatCalc.cc
  23. 2 2
      src/ConsoleStatCalc.h
  24. 2 2
      src/DHTAutoSaveCommand.cc
  25. 1 1
      src/DHTAutoSaveCommand.h
  26. 2 2
      src/DHTBucketRefreshCommand.cc
  27. 2 1
      src/DHTBucketRefreshCommand.h
  28. 11 8
      src/DHTConstants.h
  29. 6 6
      src/DHTGetPeersCommand.cc
  30. 1 1
      src/DHTMessageDispatcher.h
  31. 4 4
      src/DHTMessageDispatcherImpl.cc
  32. 4 4
      src/DHTMessageDispatcherImpl.h
  33. 2 2
      src/DHTMessageEntry.cc
  34. 2 2
      src/DHTMessageEntry.h
  35. 7 5
      src/DHTMessageTracker.cc
  36. 1 1
      src/DHTMessageTracker.h
  37. 4 4
      src/DHTMessageTrackerEntry.cc
  38. 3 3
      src/DHTMessageTrackerEntry.h
  39. 6 4
      src/DHTNode.cc
  40. 3 4
      src/DHTNode.h
  41. 2 2
      src/DHTPeerAnnounceCommand.cc
  42. 2 1
      src/DHTPeerAnnounceCommand.h
  43. 9 21
      src/DHTPeerAnnounceEntry.cc
  44. 1 1
      src/DHTPeerAnnounceEntry.h
  45. 8 15
      src/DHTPeerAnnounceStorage.cc
  46. 3 3
      src/DHTPingTask.h
  47. 3 3
      src/DHTReplaceNodeTask.h
  48. 6 6
      src/DHTSetup.cc
  49. 1 1
      src/DHTTaskFactoryImpl.cc
  50. 3 3
      src/DHTTaskFactoryImpl.h
  51. 2 2
      src/DHTTokenUpdateCommand.cc
  52. 2 1
      src/DHTTokenUpdateCommand.h
  53. 17 16
      src/DefaultBtAnnounce.cc
  54. 9 8
      src/DefaultBtAnnounce.h
  55. 17 8
      src/DefaultBtInteractive.cc
  56. 3 5
      src/DefaultBtInteractive.h
  57. 3 3
      src/DefaultBtMessageDispatcher.h
  58. 13 10
      src/DefaultPeerStorage.cc
  59. 1 1
      src/DefaultPeerStorage.h
  60. 9 23
      src/DefaultPieceStorage.cc
  61. 2 1
      src/DefaultPieceStorage.h
  62. 2 2
      src/DelayedCommand.h
  63. 1 1
      src/DownloadCommand.cc
  64. 3 3
      src/DownloadCommand.h
  65. 5 5
      src/DownloadContext.cc
  66. 1 1
      src/DownloadContext.h
  67. 30 24
      src/DownloadEngine.cc
  68. 9 12
      src/DownloadEngine.h
  69. 10 10
      src/DownloadEngineFactory.cc
  70. 1 2
      src/DownloadResult.h
  71. 5 4
      src/FileAllocationCommand.cc
  72. 5 3
      src/FileEntry.cc
  73. 4 2
      src/FtpNegotiationCommand.cc
  74. 6 3
      src/HaveEraseCommand.cc
  75. 2 1
      src/HaveEraseCommand.h
  76. 1 1
      src/HttpRequestCommand.cc
  77. 2 1
      src/HttpResponseCommand.cc
  78. 4 3
      src/HttpServerBodyCommand.cc
  79. 2 1
      src/HttpServerCommand.cc
  80. 1 1
      src/InitiateConnectionCommand.cc
  81. 3 2
      src/InitiatorMSEHandshakeCommand.cc
  82. 3 3
      src/LpdMessageDispatcher.cc
  83. 5 5
      src/LpdMessageDispatcher.h
  84. 3 7
      src/MultiUrlRequestInfo.cc
  85. 1 1
      src/Peer.cc
  86. 1 1
      src/PeerAbstractCommand.cc
  87. 6 2
      src/PeerAbstractCommand.h
  88. 7 6
      src/PeerInteractionCommand.cc
  89. 2 2
      src/PeerSessionResource.cc
  90. 1 1
      src/PieceStorage.h
  91. 2 1
      src/ReceiverMSEHandshakeCommand.cc
  92. 6 5
      src/RequestGroup.cc
  93. 3 6
      src/RequestGroup.h
  94. 4 5
      src/RequestGroupMan.cc
  95. 3 6
      src/RequestSlot.cc
  96. 11 5
      src/RequestSlot.h
  97. 4 4
      src/RpcMethodImpl.cc
  98. 2 2
      src/SaveSessionCommand.cc
  99. 2 1
      src/SaveSessionCommand.h
  100. 1 1
      src/SftpNegotiationCommand.cc

+ 7 - 5
src/AbstractCommand.cc

@@ -237,7 +237,8 @@ bool AbstractCommand::execute()
       if (req_ && fileEntry_->getLength() > 0 &&
           e_->getRequestGroupMan()->getMaxOverallDownloadSpeedLimit() == 0 &&
           requestGroup_->getMaxDownloadSpeedLimit() == 0 &&
-          serverStatTimer_.difference(global::wallclock()) >= 10) {
+          serverStatTimer_.difference(global::wallclock()) >=
+              std::chrono::seconds(10)) {
         serverStatTimer_ = global::wallclock();
         std::vector<std::pair<size_t, std::string>> usedHosts;
         if (getOption()->getAsBool(PREF_SELECT_LEAST_USED_HOST)) {
@@ -284,7 +285,7 @@ bool AbstractCommand::execute()
             A2_LOG_DEBUG("All segments are ignored.");
             // This will execute other idle Commands and let them
             // finish quickly.
-            e_->setRefreshInterval(0);
+            e_->setRefreshInterval(std::chrono::milliseconds(0));
             return true;
           }
 
@@ -386,7 +387,8 @@ bool AbstractCommand::execute()
     }
 
     Timer wakeTime(global::wallclock());
-    wakeTime.advance(getOption()->getAsInt(PREF_RETRY_WAIT));
+    wakeTime.advance(
+        std::chrono::seconds(getOption()->getAsInt(PREF_RETRY_WAIT)));
     req_->setWakeTime(wakeTime);
     return prepareForRetry(0);
   }
@@ -401,7 +403,7 @@ bool AbstractCommand::execute()
       A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, err);
     }
     requestGroup_->setHaltRequested(true);
-    getDownloadEngine()->setRefreshInterval(0);
+    getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
     return true;
   }
 }
@@ -457,7 +459,7 @@ bool AbstractCommand::prepareForRetry(time_t wait)
   }
   else {
     // We don't use wait so that Command can be executed by
-    // DownloadEngine::setRefreshInterval(0).
+    // DownloadEngine::setRefreshInterval(std::chrono::milliseconds(0)).
     command->setStatus(Command::STATUS_INACTIVE);
   }
   e_->addCommand(std::move(command));

+ 4 - 4
src/AbstractCommand.h

@@ -83,7 +83,7 @@ private:
 
   Timer checkPoint_;
   Timer serverStatTimer_;
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   bool checkSocketIsReadable_;
   bool checkSocketIsWritable_;
@@ -185,14 +185,14 @@ public:
   // check.
   void swapSocket(std::shared_ptr<SocketCore>& socket);
 
-  time_t getTimeout() const
+  std::chrono::seconds getTimeout() const
   {
     return timeout_;
   }
 
-  void setTimeout(time_t timeout)
+  void setTimeout(std::chrono::seconds timeout)
   {
-    timeout_ = timeout;
+    timeout_ = std::move(timeout);
   }
 
   void prepareForNextAction(std::unique_ptr<CheckIntegrityEntry> checkEntry);

+ 2 - 1
src/AbstractHttpServerResponseCommand.cc

@@ -119,7 +119,8 @@ bool AbstractHttpServerResponseCommand::execute()
     afterSend(httpServer_, e_);
     return true;
   } else {
-    if(timeoutTimer_.difference(global::wallclock()) >= 30) {
+    if (timeoutTimer_.difference(global::wallclock()) >=
+        std::chrono::seconds(30)) {
       A2_LOG_INFO(fmt("CUID#%" PRId64
                       " - HttpServer: Timeout while trasmitting response.",
                       getCuid()));

+ 1 - 1
src/AbstractProxyRequestCommand.cc

@@ -64,7 +64,7 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand
   (std::make_shared<HttpConnection>
    (cuid, s, std::make_shared<SocketRecvBuffer>(s)))
 {
-  setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
+  setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)));
   disableReadCheckSocket();
   setWriteCheckSocket(getSocket());
 }

+ 2 - 2
src/ActivePeerConnectionCommand.cc

@@ -60,10 +60,10 @@ ActivePeerConnectionCommand::ActivePeerConnectionCommand
 (cuid_t cuid,
  RequestGroup* requestGroup,
  DownloadEngine* e,
- time_t interval)
+ std::chrono::seconds interval)
   : Command(cuid),
     requestGroup_(requestGroup),
-    interval_(interval),
+    interval_(std::move(interval)),
     e_(e),
     numNewConnection_(5)
 {

+ 2 - 2
src/ActivePeerConnectionCommand.h

@@ -59,7 +59,7 @@ private:
   std::shared_ptr<PeerStorage> peerStorage_;
   std::shared_ptr<BtAnnounce> btAnnounce_;
 
-  time_t interval_; // UNIT: sec
+  std::chrono::seconds interval_;
   DownloadEngine* e_;
   Timer checkPoint_;
   int numNewConnection_; // the number of the connection to establish.
@@ -67,7 +67,7 @@ public:
   ActivePeerConnectionCommand(cuid_t cuid,
                               RequestGroup* requestGroup,
                               DownloadEngine* e,
-                              time_t interval);
+                              std::chrono::seconds interval);
 
   virtual ~ActivePeerConnectionCommand();
 

+ 9 - 4
src/AdaptiveURISelector.cc

@@ -96,6 +96,10 @@ std::string AdaptiveURISelector::select
   return selected;
 }
 
+namespace {
+constexpr auto MAX_TIMEOUT = std::chrono::seconds(60);
+} // namespace
+
 void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
 {
   if (requestGroup_->getTimeout()*2 >= MAX_TIMEOUT) return;
@@ -111,10 +115,11 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
   if(A2_LOG_DEBUG_ENABLED) {
     for(std::deque<std::string>::const_iterator i = uris.begin(),
           eoi = uris.end(); i != eoi; ++i) {
-      A2_LOG_DEBUG(fmt("AdaptiveURISelector: will retry server with increased"
-                       " timeout (%ld s): %s",
-                       static_cast<long int>(requestGroup_->getTimeout()),
-                       (*i).c_str()));
+      A2_LOG_DEBUG(
+          fmt("AdaptiveURISelector: will retry server with increased"
+              " timeout (%ld s): %s",
+              static_cast<long int>(requestGroup_->getTimeout().count()),
+              (*i).c_str()));
     }
   }
 }

+ 1 - 2
src/AdaptiveURISelector.h

@@ -38,6 +38,7 @@
 #include "URISelector.h"
 
 #include <memory>
+#include <chrono>
 
 namespace aria2 {
 
@@ -53,8 +54,6 @@ private:
   int nbServerToEvaluate_;
   int nbConnections_;
 
-  static const time_t MAX_TIMEOUT = 60;
-
   void mayRetryWithIncreasedTimeout(FileEntry* fileEntry);
 
   std::string selectOne(const std::deque<std::string>& uris);

+ 3 - 3
src/AutoSaveCommand.cc

@@ -38,9 +38,9 @@
 
 namespace aria2 {
 
-AutoSaveCommand::AutoSaveCommand
-(cuid_t cuid, DownloadEngine* e, time_t interval)
-  : TimeBasedCommand(cuid, e, interval, true)
+AutoSaveCommand::AutoSaveCommand(cuid_t cuid, DownloadEngine* e,
+                                 std::chrono::seconds interval)
+  : TimeBasedCommand(cuid, e, std::move(interval), true)
 {}
 
 AutoSaveCommand::~AutoSaveCommand() {}

+ 2 - 1
src/AutoSaveCommand.h

@@ -42,7 +42,8 @@ namespace aria2 {
 class AutoSaveCommand : public TimeBasedCommand
 {
 public:
-  AutoSaveCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  AutoSaveCommand(cuid_t cuid, DownloadEngine* e,
+                  std::chrono::seconds interval);
 
   virtual ~AutoSaveCommand();
 

+ 2 - 1
src/BackupIPv4ConnectCommand.cc

@@ -114,7 +114,8 @@ bool BackupIPv4ConnectCommand::execute()
     // TODO Although we check 300ms initial timeout as described in
     // RFC 6555, the interval will be much longer and around 1 second
     // due to the refresh interval mechanism in DownloadEngine.
-    if(startTime_.differenceInMillis(global::wallclock()) >= 300) {
+    if(startTime_.difference(global::wallclock()) >=
+       std::chrono::milliseconds(300)) {
       socket_ = std::make_shared<SocketCore>();
       try {
         socket_->establishConnection(ipaddr_, port_);

+ 1 - 1
src/BackupIPv4ConnectCommand.h

@@ -81,7 +81,7 @@ private:
   DownloadEngine* e_;
   Timer startTime_;
   Timer timeoutCheck_;
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 };
 
 } // namespace aria2

+ 2 - 0
src/BtAnnounce.cc

@@ -54,4 +54,6 @@ const std::string BtAnnounce::PEERS("peers");
 
 const std::string BtAnnounce::PEERS6("peers6");
 
+constexpr std::chrono::seconds BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL;
+
 } // namespace aria2

+ 2 - 2
src/BtAnnounce.h

@@ -116,7 +116,7 @@ public:
    */
   virtual void shuffleAnnounce() = 0;
 
-  virtual void overrideMinInterval(time_t interval) = 0;
+  virtual void overrideMinInterval(std::chrono::seconds interval) = 0;
 
   virtual void setTcpPort(uint16_t port) = 0;
 
@@ -138,7 +138,7 @@ public:
 
   static const std::string PEERS6;
 
-  static const time_t DEFAULT_ANNOUNCE_INTERVAL = 120;
+  constexpr static auto DEFAULT_ANNOUNCE_INTERVAL = std::chrono::seconds(120);
 };
 
 } // namespace aria2

+ 10 - 7
src/BtLeecherStateChoke.cc

@@ -47,17 +47,20 @@ namespace aria2 {
 
 BtLeecherStateChoke::BtLeecherStateChoke()
   : round_(0),
-    lastRound_(0)
+    lastRound_(Timer::zero())
 {}
 
 BtLeecherStateChoke::~BtLeecherStateChoke() {}
 
-BtLeecherStateChoke::PeerEntry::PeerEntry(const std::shared_ptr<Peer>& peer):
-  peer_(peer), downloadSpeed_(peer->calculateDownloadSpeed()),
-  // peer must be interested to us and sent block in the last 30 seconds
-  regularUnchoker_
-  (peer->peerInterested() &&
-   peer->getLastDownloadUpdate().difference(global::wallclock()) < 30) {}
+BtLeecherStateChoke::PeerEntry::PeerEntry(const std::shared_ptr<Peer>& peer)
+  : peer_(peer),
+    downloadSpeed_(peer->calculateDownloadSpeed()),
+    // peer must be interested to us and sent block in the last 30 seconds
+    regularUnchoker_(peer->peerInterested() &&
+                     peer->getLastDownloadUpdate().difference(
+                         global::wallclock()) < std::chrono::seconds(30))
+{
+}
 
 BtLeecherStateChoke::PeerEntry::PeerEntry(const PeerEntry& c)
   : peer_(c.peer_),

+ 5 - 1
src/BtSeederStateChoke.cc

@@ -47,11 +47,15 @@ namespace aria2 {
 
 BtSeederStateChoke::BtSeederStateChoke()
   : round_(0),
-    lastRound_(0)
+    lastRound_(Timer::zero())
 {}
 
 BtSeederStateChoke::~BtSeederStateChoke() {}
 
+namespace {
+constexpr auto TIME_FRAME = std::chrono::seconds(20);
+} // namespace
+
 BtSeederStateChoke::PeerEntry::PeerEntry
 (const std::shared_ptr<Peer>& peer):
   peer_(peer),

+ 0 - 1
src/BtSeederStateChoke.h

@@ -61,7 +61,6 @@ private:
     bool recentUnchoking_;
     int uploadSpeed_;
 
-    const static time_t TIME_FRAME = 20;
   public:
     PeerEntry(const std::shared_ptr<Peer>& peer);
     PeerEntry(const PeerEntry& c);

+ 7 - 6
src/BtSetup.cc

@@ -125,8 +125,9 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
     commands.push_back(std::move(c));
   }
   {
-    auto c = make_unique<ActivePeerConnectionCommand>
-      (e->newCUID(), requestGroup, e, metadataGetMode?2:10);
+    auto c = make_unique<ActivePeerConnectionCommand>(
+        e->newCUID(), requestGroup, e,
+        std::chrono::seconds(metadataGetMode ? 2 : 10));
     c->setBtRuntime(btRuntime);
     c->setPieceStorage(pieceStorage);
     c->setPeerStorage(peerStorage);
@@ -158,8 +159,8 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
   if(!metadataGetMode) {
     auto unionCri = make_unique<UnionSeedCriteria>();
     if(option->defined(PREF_SEED_TIME)) {
-      unionCri->addSeedCriteria(make_unique<TimeSeedCriteria>
-                                (option->getAsInt(PREF_SEED_TIME)*60));
+      unionCri->addSeedCriteria(make_unique<TimeSeedCriteria>(
+          std::chrono::seconds(option->getAsInt(PREF_SEED_TIME) * 60)));
     }
     {
       double ratio = option->getAsDouble(PREF_SEED_RATIO);
@@ -271,10 +272,10 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
       }
     }
   }
-  time_t btStopTimeout = option->getAsInt(PREF_BT_STOP_TIMEOUT);
+  auto btStopTimeout = option->getAsInt(PREF_BT_STOP_TIMEOUT);
   if(btStopTimeout > 0) {
     auto stopDownloadCommand = make_unique<BtStopDownloadCommand>
-      (e->newCUID(), requestGroup, e, btStopTimeout);
+      (e->newCUID(), requestGroup, e, std::chrono::seconds(btStopTimeout));
     stopDownloadCommand->setBtRuntime(btRuntime);
     stopDownloadCommand->setPieceStorage(pieceStorage);
     commands.push_back(std::move(stopDownloadCommand));

+ 4 - 4
src/BtStopDownloadCommand.cc

@@ -50,10 +50,10 @@ BtStopDownloadCommand::BtStopDownloadCommand
 (cuid_t cuid,
  RequestGroup* requestGroup,
  DownloadEngine* e,
- time_t timeout)
-  : TimeBasedCommand(cuid, e, 1),
+ std::chrono::seconds timeout)
+  : TimeBasedCommand(cuid, e, std::chrono::seconds(1)),
     requestGroup_(requestGroup),
-    timeout_(timeout)
+    timeout_(std::move(timeout))
 {}
 
 void BtStopDownloadCommand::preProcess()
@@ -66,7 +66,7 @@ void BtStopDownloadCommand::preProcess()
                         " --bt-stop-timeout option."),
                       GroupId::toHex(requestGroup_->getGID()).c_str()));
     requestGroup_->setForceHaltRequested(true);
-    getDownloadEngine()->setRefreshInterval(0);
+    getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
     enableExit();
   }
 }

+ 2 - 2
src/BtStopDownloadCommand.h

@@ -51,7 +51,7 @@ class BtStopDownloadCommand:public TimeBasedCommand {
 private:
   RequestGroup* requestGroup_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   Timer checkPoint_;
 
@@ -63,7 +63,7 @@ public:
   (cuid_t cuid,
    RequestGroup* requestGroup,
    DownloadEngine* e,
-   time_t timeout);
+   std::chrono::seconds timeout);
 
   virtual void preProcess() CXX11_OVERRIDE;
 

+ 1 - 1
src/ConnectCommand.cc

@@ -57,7 +57,7 @@ ConnectCommand::ConnectCommand(cuid_t cuid,
   : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
     proxyRequest_(proxyRequest)
 {
-  setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
+  setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)));
   disableReadCheckSocket();
   setWriteCheckSocket(getSocket());
 }

+ 6 - 5
src/ConsoleStatCalc.cc

@@ -265,10 +265,10 @@ void printProgressSummary(const RequestGroupList& groups, size_t cols,
 }
 } // namespace
 
-ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval,
+ConsoleStatCalc::ConsoleStatCalc(std::chrono::seconds summaryInterval,
                                  bool colorOutput,
                                  bool humanReadable):
-  summaryInterval_(summaryInterval),
+  summaryInterval_(std::move(summaryInterval)),
   readoutVisibility_(true),
   truncate_(true),
 #ifdef __MINGW32__
@@ -288,7 +288,8 @@ ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval,
 void
 ConsoleStatCalc::calculateStat(const DownloadEngine* e)
 {
-  if(cp_.differenceInMillis(global::wallclock())+A2_DELTA_MILLIS < 1000) {
+  if(cp_.difference(global::wallclock()) + A2_DELTA_MILLIS <
+     std::chrono::milliseconds(1000)) {
     return;
   }
   cp_ = global::wallclock();
@@ -317,8 +318,8 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e)
   }
   ColorizedStream o;
   if(e->getRequestGroupMan()->countRequestGroup() > 0) {
-    if((summaryInterval_ > 0) &&
-       lastSummaryNotified_.differenceInMillis(global::wallclock())+
+    if((summaryInterval_ > std::chrono::seconds(0)) &&
+       lastSummaryNotified_.difference(global::wallclock())+
        A2_DELTA_MILLIS >= summaryInterval_*1000) {
       lastSummaryNotified_ = global::wallclock();
       printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e,

+ 2 - 2
src/ConsoleStatCalc.h

@@ -61,7 +61,7 @@ private:
 
   Timer lastSummaryNotified_;
 
-  time_t summaryInterval_;
+  std::chrono::seconds summaryInterval_;
 
   std::unique_ptr<SizeFormatter> sizeFormatter_;
   bool readoutVisibility_;
@@ -69,7 +69,7 @@ private:
   bool isTTY_;
   bool colorOutput_;
 public:
-  ConsoleStatCalc(time_t summaryInterval, bool colorOutput = true,
+  ConsoleStatCalc(std::chrono::seconds summaryInterval, bool colorOutput = true,
                   bool humanReadable = true);
 
   virtual ~ConsoleStatCalc() {}

+ 2 - 2
src/DHTAutoSaveCommand.cc

@@ -57,8 +57,8 @@
 namespace aria2 {
 
 DHTAutoSaveCommand::DHTAutoSaveCommand
-(cuid_t cuid, DownloadEngine* e, int family, time_t interval)
-  : TimeBasedCommand{cuid, e, interval},
+(cuid_t cuid, DownloadEngine* e, int family, std::chrono::seconds interval)
+  : TimeBasedCommand{cuid, e, std::move(interval)},
     family_{family},
     routingTable_{nullptr}
 {}

+ 1 - 1
src/DHTAutoSaveCommand.h

@@ -56,7 +56,7 @@ private:
   void save();
 public:
   DHTAutoSaveCommand
-  (cuid_t cuid, DownloadEngine* e, int family, time_t interval);
+  (cuid_t cuid, DownloadEngine* e, int family, std::chrono::seconds interval);
 
   virtual ~DHTAutoSaveCommand();
 

+ 2 - 2
src/DHTBucketRefreshCommand.cc

@@ -43,8 +43,8 @@
 namespace aria2 {
 
 DHTBucketRefreshCommand::DHTBucketRefreshCommand
-(cuid_t cuid, DownloadEngine* e, time_t interval)
-  : TimeBasedCommand{cuid, e, interval},
+(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval)
+  : TimeBasedCommand{cuid, e, std::move(interval)},
     routingTable_{nullptr},
     taskQueue_{nullptr},
     taskFactory_{nullptr}

+ 2 - 1
src/DHTBucketRefreshCommand.h

@@ -53,7 +53,8 @@ private:
 
   DHTTaskFactory* taskFactory_;
 public:
-  DHTBucketRefreshCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  DHTBucketRefreshCommand(cuid_t cuid, DownloadEngine* e,
+                          std::chrono::seconds interval);
 
   virtual ~DHTBucketRefreshCommand();
 

+ 11 - 8
src/DHTConstants.h

@@ -35,6 +35,9 @@
 #ifndef D_DHT_CONSTANTS_H
 #define D_DHT_CONSTANTS_H
 
+#include "common.h"
+#include "TimerA2.h"
+
 // Increment this if major improvements or bug fixes are made in DHT
 // code. This is 2 bytes unsigned integer.
 #define DHT_VERSION 3U
@@ -46,20 +49,20 @@
 #define DHT_TOKEN_LENGTH 4
 
 // See --dht-message-timeout option.
-#define DHT_MESSAGE_TIMEOUT 10
+constexpr auto DHT_MESSAGE_TIMEOUT = std::chrono::seconds(10);
 
-#define DHT_NODE_CONTACT_INTERVAL (15*60)
+constexpr auto DHT_NODE_CONTACT_INTERVAL = std::chrono::minutes(15);
 
-#define DHT_BUCKET_REFRESH_INTERVAL (15*60)
+constexpr auto DHT_BUCKET_REFRESH_INTERVAL = std::chrono::minutes(15);
 
-#define DHT_BUCKET_REFRESH_CHECK_INTERVAL (5*60)
+constexpr auto DHT_BUCKET_REFRESH_CHECK_INTERVAL = std::chrono::minutes(5);
 
-#define DHT_PEER_ANNOUNCE_PURGE_INTERVAL (30*60)
+constexpr auto DHT_PEER_ANNOUNCE_PURGE_INTERVAL = std::chrono::minutes(30);
 
-#define DHT_PEER_ANNOUNCE_INTERVAL (15*60)
+constexpr auto DHT_PEER_ANNOUNCE_INTERVAL = std::chrono::minutes(15);
 
-#define DHT_PEER_ANNOUNCE_CHECK_INTERVAL (5*60)
+constexpr auto DHT_PEER_ANNOUNCE_CHECK_INTERVAL = std::chrono::minutes(5);
 
-#define DHT_TOKEN_UPDATE_INTERVAL (10*60)
+constexpr auto DHT_TOKEN_UPDATE_INTERVAL = std::chrono::minutes(10);
 
 #endif // D_DHT_CONSTANTS_H

+ 6 - 6
src/DHTGetPeersCommand.cc

@@ -55,13 +55,13 @@ namespace aria2 {
 
 namespace {
 
-const time_t GET_PEER_INTERVAL = (15*60);
+constexpr auto GET_PEER_INTERVAL = std::chrono::minutes(15);
 // Interval when the size of peer list is low.
-const time_t GET_PEER_INTERVAL_LOW = (5*60);
+constexpr auto GET_PEER_INTERVAL_LOW = std::chrono::minutes(5);
 // Interval when the peer list is empty.
-const time_t GET_PEER_INTERVAL_ZERO = 60;
+constexpr auto GET_PEER_INTERVAL_ZERO = std::chrono::minutes(1);
 // Interval for retry.
-const time_t GET_PEER_INTERVAL_RETRY = 5;
+constexpr auto GET_PEER_INTERVAL_RETRY = std::chrono::seconds(5);
 // Maximum retries. Try more than 5 to drop bad node.
 const int MAX_RETRIES = 10;
 
@@ -77,7 +77,7 @@ DHTGetPeersCommand::DHTGetPeersCommand
     taskQueue_{nullptr},
     taskFactory_{nullptr},
     numRetry_{0},
-    lastGetPeerTime_{0}
+    lastGetPeerTime_{Timer::zero()}
 {
   requestGroup_->increaseNumCommand();
 }
@@ -92,7 +92,7 @@ bool DHTGetPeersCommand::execute()
   if(btRuntime_->isHalt()) {
     return true;
   }
-  time_t elapsed = lastGetPeerTime_.difference(global::wallclock());
+  auto elapsed = lastGetPeerTime_.difference(global::wallclock());
   if(!task_ &&
      (elapsed >= GET_PEER_INTERVAL ||
       (((btRuntime_->lessThanMinPeers() &&

+ 1 - 1
src/DHTMessageDispatcher.h

@@ -52,7 +52,7 @@ public:
 
   virtual void
   addMessageToQueue(std::unique_ptr<DHTMessage> message,
-                    time_t timeout,
+                    std::chrono::seconds timeout,
                     std::unique_ptr<DHTMessageCallback> callback =
                     std::unique_ptr<DHTMessageCallback>{}) = 0;
 

+ 4 - 4
src/DHTMessageDispatcherImpl.cc

@@ -56,11 +56,11 @@ DHTMessageDispatcherImpl::DHTMessageDispatcherImpl
 void
 DHTMessageDispatcherImpl::addMessageToQueue
 (std::unique_ptr<DHTMessage> message,
- time_t timeout,
+ std::chrono::seconds timeout,
  std::unique_ptr<DHTMessageCallback> callback)
 {
-  messageQueue_.push_back(make_unique<DHTMessageEntry>
-                          (std::move(message), timeout, std::move(callback)));
+  messageQueue_.push_back(make_unique<DHTMessageEntry>(
+      std::move(message), std::move(timeout), std::move(callback)));
 }
 
 void
@@ -92,7 +92,7 @@ bool DHTMessageDispatcherImpl::sendMessage(DHTMessageEntry* entry)
     // DHTTask(such as DHTAbstractNodeLookupTask) don't finish
     // forever.
     if(!entry->message->isReply()) {
-      tracker_->addMessage(entry->message.get(), 0,
+      tracker_->addMessage(entry->message.get(), std::chrono::seconds(0),
                            std::move(entry->callback));
     }
   }

+ 4 - 4
src/DHTMessageDispatcherImpl.h

@@ -49,7 +49,7 @@ private:
 
   std::deque<std::unique_ptr<DHTMessageEntry>> messageQueue_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   bool sendMessage(DHTMessageEntry* msg);
 public:
@@ -57,7 +57,7 @@ public:
 
   virtual void
   addMessageToQueue(std::unique_ptr<DHTMessage> message,
-                    time_t timeout,
+                    std::chrono::seconds timeout,
                     std::unique_ptr<DHTMessageCallback> callback =
                     std::unique_ptr<DHTMessageCallback>{})
     CXX11_OVERRIDE;
@@ -72,9 +72,9 @@ public:
 
   virtual size_t countMessageInQueue() const CXX11_OVERRIDE;
 
-  void setTimeout(time_t timeout)
+  void setTimeout(std::chrono::seconds timeout)
   {
-    timeout_ = timeout;
+    timeout_ = std::move(timeout);
   }
 };
 

+ 2 - 2
src/DHTMessageEntry.cc

@@ -41,10 +41,10 @@ namespace aria2 {
 
 DHTMessageEntry::DHTMessageEntry
 (std::unique_ptr<DHTMessage> message,
- time_t timeout,
+ std::chrono::seconds timeout,
  std::unique_ptr<DHTMessageCallback> callback)
   : message{std::move(message)},
-    timeout{timeout},
+    timeout{std::move(timeout)},
     callback{std::move(callback)}
 {}
 

+ 2 - 2
src/DHTMessageEntry.h

@@ -48,11 +48,11 @@ class DHTMessageCallback;
 
 struct DHTMessageEntry {
   std::unique_ptr<DHTMessage> message;
-  time_t timeout;
+  std::chrono::seconds timeout;
   std::unique_ptr<DHTMessageCallback> callback;
 
   DHTMessageEntry(std::unique_ptr<DHTMessage> message,
-                  time_t timeout,
+                  std::chrono::seconds timeout,
                   std::unique_ptr<DHTMessageCallback> callback);
 };
 

+ 7 - 5
src/DHTMessageTracker.cc

@@ -58,14 +58,14 @@ DHTMessageTracker::DHTMessageTracker()
 
 void DHTMessageTracker::addMessage
 (DHTMessage* message,
- time_t timeout,
+ std::chrono::seconds timeout,
  std::unique_ptr<DHTMessageCallback> callback)
 {
   entries_.push_back(make_unique<DHTMessageTrackerEntry>
                      (message->getRemoteNode(),
                       message->getTransactionID(),
                       message->getMessageType(),
-                      timeout, std::move(callback)));
+                      std::move(timeout), std::move(callback)));
 }
 
 std::pair<std::unique_ptr<DHTResponseMessage>,
@@ -93,8 +93,9 @@ DHTMessageTracker::messageArrived
                                           targetNode->getIPAddress(),
                                           targetNode->getPort());
 
-        int64_t rtt = entry->getElapsedMillis();
-        A2_LOG_DEBUG(fmt("RTT is %" PRId64 "", rtt));
+        auto rtt = std::chrono::duration_cast<std::chrono::milliseconds>(
+            entry->getElapsed());
+        A2_LOG_DEBUG(fmt("RTT is %" PRId64 "", rtt.count()));
         message->getRemoteNode()->updateRTT(rtt);
         if(*targetNode != *message->getRemoteNode()) {
           // Node ID has changed. Drop previous node ID from
@@ -124,7 +125,8 @@ void DHTMessageTracker::handleTimeoutEntry(DHTMessageTrackerEntry* entry)
     auto& node = entry->getTargetNode();
     A2_LOG_DEBUG(fmt("Message timeout: To:%s:%u",
                      node->getIPAddress().c_str(), node->getPort()));
-    node->updateRTT(entry->getElapsedMillis());
+    node->updateRTT(std::chrono::duration_cast<std::chrono::milliseconds>(
+        entry->getElapsed()));
     node->timeout();
     if(node->isBad()) {
       A2_LOG_DEBUG(fmt("Marked bad: %s:%u",

+ 1 - 1
src/DHTMessageTracker.h

@@ -64,7 +64,7 @@ public:
   DHTMessageTracker();
 
   void addMessage(DHTMessage* message,
-                  time_t timeout,
+                  std::chrono::seconds timeout,
                   std::unique_ptr<DHTMessageCallback> callback =
                   std::unique_ptr<DHTMessageCallback>{});
 

+ 4 - 4
src/DHTMessageTrackerEntry.cc

@@ -46,14 +46,14 @@ DHTMessageTrackerEntry::DHTMessageTrackerEntry
 (std::shared_ptr<DHTNode> targetNode,
  std::string transactionID,
  std::string messageType,
- time_t timeout,
+ std::chrono::seconds timeout,
  std::unique_ptr<DHTMessageCallback> callback)
   : targetNode_{std::move(targetNode)},
     transactionID_{std::move(transactionID)},
     messageType_{std::move(messageType)},
     callback_{std::move(callback)},
     dispatchedTime_{global::wallclock()},
-    timeout_{timeout}
+    timeout_{std::move(timeout)}
 {}
 
 bool DHTMessageTrackerEntry::isTimeout() const
@@ -80,9 +80,9 @@ bool DHTMessageTrackerEntry::match(const std::string& transactionID, const std::
   return false;
 }
 
-int64_t DHTMessageTrackerEntry::getElapsedMillis() const
+Timer::Clock::duration DHTMessageTrackerEntry::getElapsed() const
 {
-  return dispatchedTime_.differenceInMillis(global::wallclock());
+  return dispatchedTime_.difference(global::wallclock());
 }
 
 const std::shared_ptr<DHTNode>& DHTMessageTrackerEntry::getTargetNode() const

+ 3 - 3
src/DHTMessageTrackerEntry.h

@@ -61,12 +61,12 @@ private:
 
   Timer dispatchedTime_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 public:
   DHTMessageTrackerEntry(std::shared_ptr<DHTNode> targetNode,
                          std::string transactionID,
                          std::string messageType,
-                         time_t timeout,
+                         std::chrono::seconds timeout,
                          std::unique_ptr<DHTMessageCallback> callback =
                          std::unique_ptr<DHTMessageCallback>{});
 
@@ -80,7 +80,7 @@ public:
   const std::string& getMessageType() const;
   const std::unique_ptr<DHTMessageCallback>& getCallback() const;
   std::unique_ptr<DHTMessageCallback> popCallback();
-  int64_t getElapsedMillis() const;
+  Timer::Clock::duration getElapsed() const;
 };
 
 } // namespace aria2

+ 6 - 4
src/DHTNode.cc

@@ -43,12 +43,14 @@
 
 namespace aria2 {
 
-DHTNode::DHTNode():port_(0), rtt_(0), condition_(0), lastContact_(0)
+DHTNode::DHTNode()
+  : port_(0), rtt_(0), condition_(0), lastContact_(Timer::zero())
 {
   generateID();
 }
 
-DHTNode::DHTNode(const unsigned char* id):port_(0), rtt_(0), condition_(1), lastContact_(0)
+DHTNode::DHTNode(const unsigned char* id)
+  : port_(0), rtt_(0), condition_(1), lastContact_(Timer::zero())
 {
   memcpy(id_, id, DHT_ID_LENGTH);
 }
@@ -122,12 +124,12 @@ void DHTNode::timeout()
 
 std::string DHTNode::toString() const
 {
-  return fmt("DHTNode ID=%s, Host=%s(%u), Condition=%d, RTT=%d",
+  return fmt("DHTNode ID=%s, Host=%s(%u), Condition=%d, RTT=%ld",
              util::toHex(id_, DHT_ID_LENGTH).c_str(),
              ipaddr_.c_str(),
              port_,
              condition_,
-             rtt_);
+             rtt_.count());
 }
 
 void DHTNode::setID(const unsigned char* id)

+ 3 - 4
src/DHTNode.h

@@ -52,8 +52,7 @@ private:
 
   uint16_t port_;
 
-  // in milli sec
-  int rtt_;
+  std::chrono::milliseconds rtt_;
 
   int condition_;
 
@@ -75,9 +74,9 @@ public:
     return id_;
   }
 
-  void updateRTT(int millisec)
+  void updateRTT(std::chrono::milliseconds t)
   {
-    rtt_ = millisec;
+    rtt_ = std::move(t);
   }
 
   const std::string& getIPAddress() const

+ 2 - 2
src/DHTPeerAnnounceCommand.cc

@@ -44,8 +44,8 @@
 namespace aria2 {
 
 DHTPeerAnnounceCommand::DHTPeerAnnounceCommand
-(cuid_t cuid, DownloadEngine* e, time_t interval)
-  : TimeBasedCommand{cuid, e, interval},
+(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval)
+  : TimeBasedCommand{cuid, e, std::move(interval)},
     peerAnnounceStorage_{nullptr}
 {}
 

+ 2 - 1
src/DHTPeerAnnounceCommand.h

@@ -47,7 +47,8 @@ class DHTPeerAnnounceCommand:public TimeBasedCommand {
 private:
   DHTPeerAnnounceStorage* peerAnnounceStorage_;
 public:
-  DHTPeerAnnounceCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  DHTPeerAnnounceCommand(cuid_t cuid, DownloadEngine* e,
+                         std::chrono::seconds interval);
 
   virtual ~DHTPeerAnnounceCommand();
 

+ 9 - 21
src/DHTPeerAnnounceEntry.cc

@@ -66,28 +66,16 @@ size_t DHTPeerAnnounceEntry::countPeerAddrEntry() const
   return peerAddrEntries_.size();
 }
 
-namespace {
-class FindStaleEntry {
-private:
-  time_t timeout_;
-public:
-  FindStaleEntry(time_t timeout):timeout_(timeout) {}
-
-  bool operator()(const PeerAddrEntry& entry) const
-  {
-    if(entry.getLastUpdated().difference(global::wallclock()) >= timeout_) {
-      return true;
-    } else {
-      return false;
-    }
-  }
-};
-} // namespace
-
-void DHTPeerAnnounceEntry::removeStalePeerAddrEntry(time_t timeout)
+void DHTPeerAnnounceEntry::removeStalePeerAddrEntry(
+    const std::chrono::seconds& timeout)
 {
-  peerAddrEntries_.erase(std::remove_if(peerAddrEntries_.begin(), peerAddrEntries_.end(),
-                                        FindStaleEntry(timeout)), peerAddrEntries_.end());
+  peerAddrEntries_.erase(
+      std::remove_if(std::begin(peerAddrEntries_), std::end(peerAddrEntries_),
+                     [&timeout](const PeerAddrEntry& entry) {
+        return entry.getLastUpdated().difference(global::wallclock()) >=
+               timeout;
+      }),
+      std::end(peerAddrEntries_));
 }
 
 bool DHTPeerAnnounceEntry::empty() const

+ 1 - 1
src/DHTPeerAnnounceEntry.h

@@ -71,7 +71,7 @@ public:
     return peerAddrEntries_;
   }
 
-  void removeStalePeerAddrEntry(time_t timeout);
+  void removeStalePeerAddrEntry(const std::chrono::seconds& timeout);
 
   bool empty() const;
 

+ 8 - 15
src/DHTPeerAnnounceStorage.cc

@@ -108,24 +108,16 @@ void DHTPeerAnnounceStorage::getPeers(std::vector<std::shared_ptr<Peer> >& peers
   }
 }
 
-namespace {
-class RemoveStalePeerAddrEntry
-{
-public:
-  void operator()(const std::shared_ptr<DHTPeerAnnounceEntry>& e)
-  {
-    e->removeStalePeerAddrEntry(DHT_PEER_ANNOUNCE_PURGE_INTERVAL);
-  }
-};
-} // namespace
-
 void DHTPeerAnnounceStorage::handleTimeout()
 {
   A2_LOG_DEBUG(fmt("Now purge peer announces(%lu entries) which are timed out.",
                    static_cast<unsigned long>(entries_.size())));
-  std::for_each(entries_.begin(), entries_.end(), RemoveStalePeerAddrEntry());
-  for(auto i = entries_.begin(),
-        eoi = entries_.end(); i != eoi;) {
+  std::for_each(std::begin(entries_), std::end(entries_),
+                [](const std::shared_ptr<DHTPeerAnnounceEntry>& e) {
+    e->removeStalePeerAddrEntry(DHT_PEER_ANNOUNCE_PURGE_INTERVAL);
+  });
+
+  for(auto i = std::begin(entries_); i != std::end(entries_); ) {
     if((*i)->empty()) {
       entries_.erase(i++);
     } else {
@@ -140,7 +132,8 @@ void DHTPeerAnnounceStorage::announcePeer()
 {
   A2_LOG_DEBUG("Now announcing peer.");
   for (auto& e: entries_) {
-    if(e->getLastUpdated().difference(global::wallclock()) < DHT_PEER_ANNOUNCE_INTERVAL) {
+    if (e->getLastUpdated().difference(global::wallclock()) <
+        DHT_PEER_ANNOUNCE_INTERVAL) {
       continue;
     }
     e->notifyUpdate();

+ 3 - 3
src/DHTPingTask.h

@@ -52,7 +52,7 @@ private:
 
   bool pingSuccessful_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   void addMessage();
 public:
@@ -66,9 +66,9 @@ public:
 
   void onTimeout(const std::shared_ptr<DHTNode>& node);
 
-  void setTimeout(time_t timeout)
+  void setTimeout(std::chrono::seconds timeout)
   {
-    timeout_ = timeout;
+    timeout_ = std::move(timeout);
   }
 
   bool isPingSuccessful() const;

+ 3 - 3
src/DHTReplaceNodeTask.h

@@ -51,7 +51,7 @@ private:
 
   int numRetry_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   void sendMessage();
 public:
@@ -66,9 +66,9 @@ public:
 
   void onTimeout(const std::shared_ptr<DHTNode>& node);
 
-  void setTimeout(time_t timeout)
+  void setTimeout(std::chrono::seconds timeout)
   {
-    timeout_ = timeout;
+    timeout_ = std::move(timeout);
   }
 };
 

+ 6 - 6
src/DHTSetup.cc

@@ -148,13 +148,13 @@ std::vector<std::unique_ptr<Command>> DHTSetup::setup
     auto tokenTracker = make_unique<DHTTokenTracker>();
     // For now, UDPTrackerClient was enabled along with DHT
     auto udpTrackerClient = std::make_shared<UDPTrackerClient>();
-    const time_t messageTimeout =
-      e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT);
+    const auto messageTimeout =
+        e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT);
     // wiring up
     tracker->setRoutingTable(routingTable.get());
     tracker->setMessageFactory(factory.get());
 
-    dispatcher->setTimeout(messageTimeout);
+    dispatcher->setTimeout(std::chrono::seconds(messageTimeout));
 
     receiver->setMessageFactory(factory.get());
     receiver->setRoutingTable(routingTable.get());
@@ -164,7 +164,7 @@ std::vector<std::unique_ptr<Command>> DHTSetup::setup
     taskFactory->setMessageDispatcher(dispatcher.get());
     taskFactory->setMessageFactory(factory.get());
     taskFactory->setTaskQueue(taskQueue.get());
-    taskFactory->setTimeout(messageTimeout);
+    taskFactory->setTimeout(std::chrono::seconds(messageTimeout));
 
     routingTable->setTaskQueue(taskQueue.get());
     routingTable->setTaskFactory(taskFactory.get());
@@ -234,8 +234,8 @@ std::vector<std::unique_ptr<Command>> DHTSetup::setup
       tempCommands.push_back(std::move(command));
     }
     {
-      auto command = make_unique<DHTAutoSaveCommand>
-        (e->newCUID(), e, family, 30*60);
+      auto command = make_unique<DHTAutoSaveCommand>(e->newCUID(), e, family,
+                                                     std::chrono::minutes(30));
       command->setLocalNode(localNode);
       command->setRoutingTable(routingTable.get());
       tempCommands.push_back(std::move(command));

+ 1 - 1
src/DHTTaskFactoryImpl.cc

@@ -64,7 +64,7 @@ std::shared_ptr<DHTTask>
 DHTTaskFactoryImpl::createPingTask(const std::shared_ptr<DHTNode>& remoteNode,
                                    int numRetry)
 {
-  std::shared_ptr<DHTPingTask> task(new DHTPingTask(remoteNode, numRetry));
+  auto task = std::make_shared<DHTPingTask>(remoteNode, numRetry);
   task->setTimeout(timeout_);
   setCommonProperty(task);
   return task;

+ 3 - 3
src/DHTTaskFactoryImpl.h

@@ -59,7 +59,7 @@ private:
 
   DHTTaskQueue* taskQueue_;
 
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   void setCommonProperty(const std::shared_ptr<DHTAbstractTask>& task);
 public:
@@ -100,9 +100,9 @@ public:
 
   void setLocalNode(const std::shared_ptr<DHTNode>& localNode);
 
-  void setTimeout(time_t timeout)
+  void setTimeout(std::chrono::seconds timeout)
   {
-    timeout_ = timeout;
+    timeout_ = std::move(timeout);
   }
 };
 

+ 2 - 2
src/DHTTokenUpdateCommand.cc

@@ -44,8 +44,8 @@
 namespace aria2 {
 
 DHTTokenUpdateCommand::DHTTokenUpdateCommand
-(cuid_t cuid, DownloadEngine* e, time_t interval)
-  : TimeBasedCommand{cuid, e, interval},
+(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval)
+  : TimeBasedCommand{cuid, e, std::move(interval)},
     tokenTracker_{nullptr}
 {}
 

+ 2 - 1
src/DHTTokenUpdateCommand.h

@@ -47,7 +47,8 @@ class DHTTokenUpdateCommand:public TimeBasedCommand {
 private:
   DHTTokenTracker* tokenTracker_;
 public:
-  DHTTokenUpdateCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  DHTTokenUpdateCommand(cuid_t cuid, DownloadEngine* e,
+                        std::chrono::seconds interval);
 
   virtual ~DHTTokenUpdateCommand();
 

+ 17 - 16
src/DefaultBtAnnounce.cc

@@ -61,10 +61,10 @@ DefaultBtAnnounce::DefaultBtAnnounce
 (DownloadContext* downloadContext, const Option* option)
   : downloadContext_{downloadContext},
     trackers_(0),
-    prevAnnounceTimer_(0),
+    prevAnnounceTimer_(Timer::zero()),
     interval_(DEFAULT_ANNOUNCE_INTERVAL),
     minInterval_(DEFAULT_ANNOUNCE_INTERVAL),
-    userDefinedInterval_(0),
+    userDefinedInterval_(std::chrono::seconds(0)),
     complete_(0),
     incomplete_(0),
     announceList_(bittorrent::getTorrentAttrs(downloadContext)->announceList),
@@ -77,12 +77,11 @@ DefaultBtAnnounce::~DefaultBtAnnounce() {
 }
 
 bool DefaultBtAnnounce::isDefaultAnnounceReady() {
-  return
-    (trackers_ == 0 &&
-     prevAnnounceTimer_.
-     difference(global::wallclock()) >= (userDefinedInterval_==0?
-                                       minInterval_:userDefinedInterval_) &&
-     !announceList_.allTiersFailed());
+  return (trackers_ == 0 &&
+          prevAnnounceTimer_.difference(global::wallclock()) >=
+              (userDefinedInterval_.count() == 0 ? minInterval_
+                                                 : userDefinedInterval_) &&
+          !announceList_.allTiersFailed());
 }
 
 bool DefaultBtAnnounce::isStoppedAnnounceReady() {
@@ -305,13 +304,14 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
   }
   const Integer* ival = downcast<Integer>(dict->get(BtAnnounce::INTERVAL));
   if(ival && ival->i() > 0) {
-    interval_ = ival->i();
-    A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_)));
+    interval_ = std::chrono::seconds(ival->i());
+    A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_.count())));
   }
   const Integer* mival = downcast<Integer>(dict->get(BtAnnounce::MIN_INTERVAL));
   if(mival && mival->i() > 0) {
-    minInterval_ = mival->i();
-    A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast<long int>(minInterval_)));
+    minInterval_ = std::chrono::seconds(mival->i());
+    A2_LOG_DEBUG(
+        fmt("Min interval:%ld", static_cast<long int>(minInterval_.count())));
     minInterval_ = std::min(minInterval_, interval_);
   } else {
     // Use interval as a minInterval if minInterval is not supplied.
@@ -355,8 +355,9 @@ void DefaultBtAnnounce::processUDPTrackerResponse
   const std::shared_ptr<UDPTrackerReply>& reply = req->reply;
   A2_LOG_DEBUG("Now processing UDP tracker response.");
   if(reply->interval > 0) {
-    minInterval_ = reply->interval;
-    A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast<long int>(minInterval_)));
+    minInterval_ = std::chrono::seconds(reply->interval);
+    A2_LOG_DEBUG(
+        fmt("Min interval:%ld", static_cast<long int>(minInterval_.count())));
     interval_ = minInterval_;
   }
   complete_ = reply->seeders;
@@ -401,9 +402,9 @@ void DefaultBtAnnounce::setPeerStorage
   peerStorage_ = peerStorage;
 }
 
-void DefaultBtAnnounce::overrideMinInterval(time_t interval)
+void DefaultBtAnnounce::overrideMinInterval(std::chrono::seconds interval)
 {
-  minInterval_ = interval;
+  minInterval_ = std::move(interval);
 }
 
 } // namespace aria2

+ 9 - 8
src/DefaultBtAnnounce.h

@@ -53,9 +53,9 @@ private:
   DownloadContext* downloadContext_;
   int trackers_;
   Timer prevAnnounceTimer_;
-  time_t interval_;
-  time_t minInterval_;
-  time_t userDefinedInterval_;
+  std::chrono::seconds interval_;
+  std::chrono::seconds minInterval_;
+  std::chrono::seconds userDefinedInterval_;
   int complete_;
   int incomplete_;
   AnnounceList announceList_;
@@ -129,7 +129,8 @@ public:
 
   virtual void shuffleAnnounce() CXX11_OVERRIDE;
 
-  virtual void overrideMinInterval(time_t interval) CXX11_OVERRIDE;
+  virtual void
+  overrideMinInterval(std::chrono::seconds interval) CXX11_OVERRIDE;
 
   virtual void setTcpPort(uint16_t port) CXX11_OVERRIDE
   {
@@ -138,12 +139,12 @@ public:
 
   void setRandomizer(Randomizer* randomizer);
 
-  time_t getInterval() const
+  const std::chrono::seconds& getInterval() const
   {
     return interval_;
   }
 
-  time_t getMinInterval() const
+  const std::chrono::seconds& getMinInterval() const
   {
     return minInterval_;
   }
@@ -163,9 +164,9 @@ public:
     return trackerId_;
   }
 
-  void setUserDefinedInterval(time_t interval)
+  void setUserDefinedInterval(std::chrono::seconds interval)
   {
-    userDefinedInterval_ = interval;
+    userDefinedInterval_ = std::move(interval);
   }
 };
 

+ 17 - 8
src/DefaultBtInteractive.cc

@@ -172,10 +172,10 @@ DefaultBtInteractive::receiveAndSendHandshake()
 
 void DefaultBtInteractive::doPostHandshakeProcessing() {
   // Set time 0 to haveTimer to cache http/ftp download piece completion
-  haveTimer_.reset(0);
+  haveTimer_ = Timer::zero();
   keepAliveTimer_ = global::wallclock();
   floodingTimer_ = global::wallclock();
-  pexTimer_.reset(0);
+  pexTimer_ = Timer::zero();
   if(peer_->isExtendedMessagingEnabled()) {
     addHandshakeExtendedMessageToQueue();
   }
@@ -254,9 +254,12 @@ void DefaultBtInteractive::decideChoking() {
   }
 }
 
+namespace {
+constexpr auto MAX_HAVE_DELAY_SEC = std::chrono::seconds(10);
+} // namespace
+
 void DefaultBtInteractive::checkHave() {
   const size_t MIN_HAVE_PACK_SIZE = 20;
-  const time_t MAX_HAVE_DELAY_SEC = 10;
   pieceStorage_->getAdvertisedPieceIndexes(haveIndexes_, cuid_, haveTimer_);
   haveTimer_ = global::wallclock();
   if(haveIndexes_.size() >= MIN_HAVE_PACK_SIZE) {
@@ -430,6 +433,10 @@ void DefaultBtInteractive::sendPendingMessage() {
   dispatcher_->sendMessages();
 }
 
+namespace {
+constexpr auto FLOODING_CHECK_INTERVAL = std::chrono::seconds(5);
+} // namespace
+
 void DefaultBtInteractive::detectMessageFlooding() {
   if(floodingTimer_.
      difference(global::wallclock()) >= FLOODING_CHECK_INTERVAL) {
@@ -445,13 +452,13 @@ void DefaultBtInteractive::detectMessageFlooding() {
 
 void DefaultBtInteractive::checkActiveInteraction()
 {
-  time_t inactiveTime = inactiveTimer_.difference(global::wallclock());
+  auto inactiveTime = inactiveTimer_.difference(global::wallclock());
   // To allow aria2 to accept mutially interested peer, disconnect uninterested
   // peer.
   {
     const time_t interval = 30;
     if(!peer_->amInterested() && !peer_->peerInterested() &&
-       inactiveTime >= interval) {
+       inactiveTime >= std::chrono::seconds(interval)) {
       peer_->setDisconnectedGracefully(true);
       // TODO change the message
       throw DL_ABORT_EX
@@ -465,7 +472,7 @@ void DefaultBtInteractive::checkActiveInteraction()
   // are disconnected in a certain time period.
   {
     const time_t interval = 60;
-    if(inactiveTime >= interval) {
+    if(inactiveTime >= std::chrono::seconds(interval)) {
       peer_->setDisconnectedGracefully(true);
       throw DL_ABORT_EX
         (fmt(EX_DROP_INACTIVE_CONNECTION,
@@ -522,7 +529,8 @@ void DefaultBtInteractive::doInteractionProcessing() {
           dispatcher_->addMessageToQueue(std::move(i));
         }
       }
-      if(perSecTimer_.difference(global::wallclock()) >= 1) {
+      if(perSecTimer_.difference(global::wallclock()) >=
+         std::chrono::seconds(1)) {
         perSecTimer_ = global::wallclock();
         // Drop timeout request after queuing message to give a chance
         // to other connection to request piece.
@@ -540,7 +548,8 @@ void DefaultBtInteractive::doInteractionProcessing() {
     checkActiveInteraction();
     decideChoking();
     detectMessageFlooding();
-    if(perSecTimer_.difference(global::wallclock()) >= 1) {
+    if(perSecTimer_.difference(global::wallclock()) >=
+       std::chrono::seconds(1)) {
       perSecTimer_ = global::wallclock();
       dispatcher_->checkRequestSlotAndDoNecessaryThing();
     }

+ 3 - 5
src/DefaultBtInteractive.h

@@ -132,7 +132,7 @@ private:
   Timer inactiveTimer_;
   Timer pexTimer_;
   Timer perSecTimer_;
-  time_t keepAliveInterval_;
+  std::chrono::seconds keepAliveInterval_;
   bool utPexEnabled_;
   bool dhtEnabled_;
 
@@ -147,8 +147,6 @@ private:
   std::vector<size_t> haveIndexes_;
   Timer haveLastSent_;
 
-  static const time_t FLOODING_CHECK_INTERVAL = 5;
-
   void addBitfieldMessageToQueue();
   void addAllowedFastMessageToQueue();
   void addHandshakeExtendedMessageToQueue();
@@ -224,8 +222,8 @@ public:
   void setExtensionMessageRegistry
   (std::unique_ptr<ExtensionMessageRegistry> registry);
 
-  void setKeepAliveInterval(time_t keepAliveInterval) {
-    keepAliveInterval_ = keepAliveInterval;
+  void setKeepAliveInterval(std::chrono::seconds keepAliveInterval) {
+    keepAliveInterval_ = std::move(keepAliveInterval);
   }
 
   void setUTPexEnabled(bool f)

+ 3 - 3
src/DefaultBtMessageDispatcher.h

@@ -62,7 +62,7 @@ private:
   BtMessageFactory* messageFactory_;
   std::shared_ptr<Peer> peer_;
   RequestGroupMan* requestGroupMan_;
-  time_t requestTimeout_;
+  std::chrono::seconds requestTimeout_;
 public:
   DefaultBtMessageDispatcher();
 
@@ -140,9 +140,9 @@ public:
     cuid_ = cuid;
   }
 
-  void setRequestTimeout(time_t requestTimeout)
+  void setRequestTimeout(std::chrono::seconds requestTimeout)
   {
-    requestTimeout_ = requestTimeout;
+    requestTimeout_ = std::move(requestTimeout);
   }
 
   void setPeerConnection(PeerConnection* peerConnection)

+ 13 - 10
src/DefaultPeerStorage.cc

@@ -62,7 +62,7 @@ DefaultPeerStorage::DefaultPeerStorage()
   : maxPeerListSize_(MAX_PEER_LIST_SIZE),
     seederStateChoke_(make_unique<BtSeederStateChoke>()),
     leecherStateChoke_(make_unique<BtLeecherStateChoke>()),
-    lastTransferStatMapUpdated_(0)
+    lastTransferStatMapUpdated_(Timer::zero())
 {}
 
 DefaultPeerStorage::~DefaultPeerStorage()
@@ -183,11 +183,11 @@ bool DefaultPeerStorage::isPeerAvailable() {
 bool DefaultPeerStorage::isBadPeer(const std::string& ipaddr)
 {
   auto i = badPeers_.find(ipaddr);
-  if(i == badPeers_.end()) {
+  if(i == std::end(badPeers_)) {
     return false;
   }
 
-  if(global::wallclock().getTime() >= (*i).second) {
+  if((*i).second <= global::wallclock()) {
     badPeers_.erase(i);
     return false;
   }
@@ -197,10 +197,10 @@ bool DefaultPeerStorage::isBadPeer(const std::string& ipaddr)
 
 void DefaultPeerStorage::addBadPeer(const std::string& ipaddr)
 {
-  if(lastBadPeerCleaned_.difference(global::wallclock()) >= 3600) {
-    for(auto i = badPeers_.begin(),
-          eoi = badPeers_.end(); i != eoi;) {
-      if(global::wallclock().getTime() >= (*i).second) {
+  if(lastBadPeerCleaned_.difference(global::wallclock()) >=
+     std::chrono::hours(1)) {
+    for(auto i = std::begin(badPeers_); i != std::end(badPeers_);) {
+      if((*i).second <= global::wallclock()) {
         A2_LOG_DEBUG(fmt("Purge %s from bad peer", (*i).first.c_str()));
         badPeers_.erase(i++);
         // badPeers_.end() will not be invalidated.
@@ -212,8 +212,11 @@ void DefaultPeerStorage::addBadPeer(const std::string& ipaddr)
   }
   A2_LOG_DEBUG(fmt("Added %s as bad peer", ipaddr.c_str()));
   // We use variable timeout to avoid many bad peers wake up at once.
-  badPeers_[ipaddr] = global::wallclock().getTime()+
-    std::max(SimpleRandomizer::getInstance()->getRandomNumber(601), 120L);
+  auto t = global::wallclock();
+  t.advance(std::chrono::seconds(
+      std::max(SimpleRandomizer::getInstance()->getRandomNumber(601), 120L)));
+
+  badPeers_[ipaddr] = std::move(t);
 }
 
 void DefaultPeerStorage::deleteUnusedPeer(size_t delSize) {
@@ -281,7 +284,7 @@ void DefaultPeerStorage::returnPeer(const std::shared_ptr<Peer>& peer)
 
 bool DefaultPeerStorage::chokeRoundIntervalElapsed()
 {
-  const time_t CHOKE_ROUND_INTERVAL = 10;
+  constexpr auto CHOKE_ROUND_INTERVAL = std::chrono::seconds(10);
   if(pieceStorage_->downloadFinished()) {
     return seederStateChoke_->getLastRound().
       difference(global::wallclock()) >= CHOKE_ROUND_INTERVAL;

+ 1 - 1
src/DefaultPeerStorage.h

@@ -71,7 +71,7 @@ private:
 
   Timer lastTransferStatMapUpdated_;
 
-  std::map<std::string, time_t> badPeers_;
+  std::map<std::string, Timer> badPeers_;
   Timer lastBadPeerCleaned_;
 
   bool isPeerAlreadyAdded(const std::shared_ptr<Peer>& peer);

+ 9 - 23
src/DefaultPieceStorage.cc

@@ -725,32 +725,18 @@ DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
   }
 }
 
-namespace {
-class FindElapsedHave
+void
+DefaultPieceStorage::removeAdvertisedPiece(const std::chrono::seconds& elapsed)
 {
-private:
-  time_t elapsed;
-public:
-  FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
-
-  bool operator()(const HaveEntry& have) {
-    if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) {
-      return true;
-    } else {
-      return false;
-    }
-  }
-};
-} // namespace
+  auto itr = std::find_if(std::begin(haves_), std::end(haves_),
+                          [&elapsed](const HaveEntry& have) {
+    return have.getRegisteredTime().difference(global::wallclock()) >= elapsed;
+  });
 
-void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
-{
-  auto itr = std::find_if(haves_.begin(), haves_.end(),
-                          FindElapsedHave(elapsed));
-  if(itr != haves_.end()) {
+  if(itr != std::end(haves_)) {
     A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
-                     static_cast<unsigned long>(haves_.end()-itr)));
-    haves_.erase(itr, haves_.end());
+                     static_cast<unsigned long>(std::end(haves_) - itr)));
+    haves_.erase(itr, std::end(haves_));
   }
 }
 

+ 2 - 1
src/DefaultPieceStorage.h

@@ -262,7 +262,8 @@ public:
                             cuid_t myCuid, const Timer& lastCheckTime)
     CXX11_OVERRIDE;
 
-  virtual void removeAdvertisedPiece(time_t elapsed) CXX11_OVERRIDE;
+  virtual void
+  removeAdvertisedPiece(const std::chrono::seconds& elapsed) CXX11_OVERRIDE;
 
   virtual void markAllPiecesDone() CXX11_OVERRIDE;
 

+ 2 - 2
src/DelayedCommand.h

@@ -59,9 +59,9 @@ public:
   }
 
 public:
-  DelayedCommand(cuid_t cuid, DownloadEngine* e, time_t delay,
+  DelayedCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds delay,
                  std::unique_ptr<Command> command, bool noWait)
-    : TimeBasedCommand(cuid, e, delay),
+    : TimeBasedCommand(cuid, e, std::move(delay)),
       command_{std::move(command)},
       noWait_{noWait}
   {

+ 1 - 1
src/DownloadCommand.cc

@@ -328,7 +328,7 @@ bool DownloadCommand::prepareForNextSegment() {
     // Following 2lines are needed for DownloadEngine to detect
     // completed RequestGroups without 1sec delay.
     getDownloadEngine()->setNoWait(true);
-    getDownloadEngine()->setRefreshInterval(0);
+    getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
     return true;
   } else {
     // The number of segments should be 1 in order to pass through the next

+ 3 - 3
src/DownloadCommand.h

@@ -53,7 +53,7 @@ private:
 
   std::unique_ptr<MessageDigest> messageDigest_;
 
-  time_t startupIdleTime_;
+  std::chrono::seconds startupIdleTime_;
 
   int lowestDownloadSpeedLimit_;
 
@@ -99,9 +99,9 @@ public:
 
   void installStreamFilter(std::unique_ptr<StreamFilter> streamFilter);
 
-  void setStartupIdleTime(time_t startupIdleTime)
+  void setStartupIdleTime(std::chrono::seconds startupIdleTime)
   {
-    startupIdleTime_ = startupIdleTime;
+    startupIdleTime_ = std::move(startupIdleTime);
   }
 
   void setLowestDownloadSpeedLimit(int lowestDownloadSpeedLimit)

+ 5 - 5
src/DownloadContext.cc

@@ -50,7 +50,7 @@ namespace aria2 {
 DownloadContext::DownloadContext()
   : ownerRequestGroup_(nullptr),
     attrs_(MAX_CTX_ATTR),
-    downloadStopTime_(0),
+    downloadStopTime_(Timer::zero()),
     pieceLength_(0),
     checksumVerified_(false),
     knowsTotalLength_(true),
@@ -62,7 +62,7 @@ DownloadContext::DownloadContext(int32_t pieceLength,
                                  std::string path)
   : ownerRequestGroup_(nullptr),
     attrs_(MAX_CTX_ATTR),
-    downloadStopTime_(0),
+    downloadStopTime_(Timer::zero()),
     pieceLength_(pieceLength),
     checksumVerified_(false),
     knowsTotalLength_(true),
@@ -76,7 +76,7 @@ DownloadContext::~DownloadContext() {}
 
 void DownloadContext::resetDownloadStartTime()
 {
-  downloadStopTime_.reset(0);
+  downloadStopTime_ = Timer::zero();
   netStat_.downloadStart();
 }
 
@@ -86,10 +86,10 @@ void DownloadContext::resetDownloadStopTime()
   netStat_.downloadStop();
 }
 
-int64_t DownloadContext::calculateSessionTime() const
+Timer::Clock::duration DownloadContext::calculateSessionTime() const
 {
   const Timer& startTime = netStat_.getDownloadStartTime();
-  return startTime.differenceInMillis(downloadStopTime_);
+  return startTime.difference(downloadStopTime_);
 }
 
 std::shared_ptr<FileEntry>

+ 1 - 1
src/DownloadContext.h

@@ -222,7 +222,7 @@ public:
     return downloadStopTime_;
   }
 
-  int64_t calculateSessionTime() const;
+  Timer::Clock::duration calculateSessionTime() const;
 
   // Returns FileEntry at given offset. std::shared_ptr<FileEntry>() is
   // returned if no such FileEntry is found.

+ 30 - 24
src/DownloadEngine.cc

@@ -90,12 +90,16 @@ volatile sig_atomic_t globalHaltRequested = 0;
 
 } // namespace global
 
+namespace {
+constexpr auto DEFAULT_REFRESH_INTERVAL = std::chrono::seconds(1);
+} // namespace
+
 DownloadEngine::DownloadEngine(std::unique_ptr<EventPoll> eventPoll)
   : eventPoll_(std::move(eventPoll)),
     haltRequested_(0),
     noWait_(true),
     refreshInterval_(DEFAULT_REFRESH_INTERVAL),
-    lastRefresh_(0),
+    lastRefresh_(Timer::zero()),
     cookieStorage_(make_unique<CookieStorage>()),
 #ifdef ENABLE_BITTORRENT
     btRegistry_(make_unique<BtRegistry>()),
@@ -164,7 +168,7 @@ int DownloadEngine::run(bool oneshot)
     noWait_ = false;
     global::wallclock().reset();
     calculateStatistics();
-    if(lastRefresh_.differenceInMillis(global::wallclock())+A2_DELTA_MILLIS >=
+    if(lastRefresh_.difference(global::wallclock())+A2_DELTA_MILLIS >=
        refreshInterval_) {
       refreshInterval_ = DEFAULT_REFRESH_INTERVAL;
       lastRefresh_ = global::wallclock();
@@ -188,9 +192,10 @@ void DownloadEngine::waitData()
   if(noWait_) {
     tv.tv_sec = tv.tv_usec = 0;
   } else {
-    lldiv_t qr = lldiv(refreshInterval_*1000, 1000000);
-    tv.tv_sec = qr.quot;
-    tv.tv_usec = qr.rem;
+    auto t =
+        std::chrono::duration_cast<std::chrono::microseconds>(refreshInterval_);
+    tv.tv_sec = t.count() / 1000000;
+    tv.tv_usec = t.count() % 1000000;
   }
   eventPoll_->poll(tv);
 }
@@ -245,7 +250,7 @@ void DownloadEngine::afterEachIteration()
     requestHalt();
     global::globalHaltRequested = 2;
     setNoWait(true);
-    setRefreshInterval(0);
+    setRefreshInterval(std::chrono::milliseconds(0));
     return;
   }
 
@@ -254,7 +259,7 @@ void DownloadEngine::afterEachIteration()
     requestForceHalt();
     global::globalHaltRequested = 4;
     setNoWait(true);
-    setRefreshInterval(0);
+    setRefreshInterval(std::chrono::milliseconds(0));
     return;
   }
 }
@@ -307,7 +312,8 @@ void DownloadEngine::poolSocket(const std::string& key,
   std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry);
   socketPool_.insert(p);
 
-  if(lastSocketPoolScan_.difference(global::wallclock()) < 60) {
+  if(lastSocketPoolScan_.difference(global::wallclock()) <
+     std::chrono::minutes(1)) {
     return;
   }
   std::multimap<std::string, SocketPoolEntry> newPool;
@@ -351,9 +357,9 @@ void DownloadEngine::poolSocket
  uint16_t proxyport,
  const std::shared_ptr<SocketCore>& sock,
  const std::string& options,
- time_t timeout)
+ std::chrono::seconds timeout)
 {
-  SocketPoolEntry e(sock, options, timeout);
+  SocketPoolEntry e(sock, options, std::move(timeout));
   poolSocket(createSockPoolKey(ipaddr, port, username, proxyhost, proxyport),e);
 }
 
@@ -363,9 +369,9 @@ void DownloadEngine::poolSocket
  const std::string& proxyhost,
  uint16_t proxyport,
  const std::shared_ptr<SocketCore>& sock,
- time_t timeout)
+ std::chrono::seconds timeout)
 {
-  SocketPoolEntry e(sock, timeout);
+  SocketPoolEntry e(sock, std::move(timeout));
   poolSocket(createSockPoolKey(ipaddr, port, A2STR::NIL,proxyhost,proxyport),e);
 }
 
@@ -388,20 +394,20 @@ bool getPeerInfo(std::pair<std::string, uint16_t>& res,
 void DownloadEngine::poolSocket(const std::shared_ptr<Request>& request,
                                 const std::shared_ptr<Request>& proxyRequest,
                                 const std::shared_ptr<SocketCore>& socket,
-                                time_t timeout)
+                                std::chrono::seconds timeout)
 {
   if(proxyRequest) {
     // If proxy is defined, then pool socket with its hostname.
     poolSocket(request->getHost(), request->getPort(),
                proxyRequest->getHost(), proxyRequest->getPort(),
-               socket, timeout);
+               socket, std::move(timeout));
     return;
   }
 
   std::pair<std::string, uint16_t> peerInfo;
   if(getPeerInfo(peerInfo, socket)) {
     poolSocket(peerInfo.first, peerInfo.second,
-                A2STR::NIL, 0, socket, timeout);
+               A2STR::NIL, 0, socket, std::move(timeout));
   }
 }
 
@@ -411,20 +417,20 @@ void DownloadEngine::poolSocket
  const std::shared_ptr<Request>& proxyRequest,
  const std::shared_ptr<SocketCore>& socket,
  const std::string& options,
- time_t timeout)
+ std::chrono::seconds timeout)
 {
   if(proxyRequest) {
     // If proxy is defined, then pool socket with its hostname.
     poolSocket(request->getHost(), request->getPort(), username,
                proxyRequest->getHost(), proxyRequest->getPort(),
-               socket, options, timeout);
+               socket, options, std::move(timeout));
     return;
   }
 
   std::pair<std::string, uint16_t> peerInfo;
   if(getPeerInfo(peerInfo, socket)) {
     poolSocket(peerInfo.first, peerInfo.second, username,
-                A2STR::NIL, 0, socket, options, timeout);
+               A2STR::NIL, 0, socket, options, std::move(timeout));
   }
 }
 
@@ -512,16 +518,16 @@ DownloadEngine::popPooledSocket
 DownloadEngine::SocketPoolEntry::SocketPoolEntry
 (const std::shared_ptr<SocketCore>& socket,
  const std::string& options,
- time_t timeout)
+ std::chrono::seconds timeout)
   : socket_(socket),
     options_(options),
-    timeout_(timeout)
+    timeout_(std::move(timeout))
 {}
 
 DownloadEngine::SocketPoolEntry::SocketPoolEntry
-(const std::shared_ptr<SocketCore>& socket, time_t timeout)
+(const std::shared_ptr<SocketCore>& socket, std::chrono::seconds timeout)
   : socket_(socket),
-    timeout_(timeout)
+    timeout_(std::move(timeout))
 {}
 
 DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
@@ -577,9 +583,9 @@ const std::unique_ptr<CookieStorage>& DownloadEngine::getCookieStorage() const
   return cookieStorage_;
 }
 
-void DownloadEngine::setRefreshInterval(int64_t interval)
+void DownloadEngine::setRefreshInterval(std::chrono::milliseconds interval)
 {
-  refreshInterval_ = std::min(static_cast<int64_t>(999), interval);
+  refreshInterval_ = std::move(interval);
 }
 
 void DownloadEngine::addCommand

+ 9 - 12
src/DownloadEngine.h

@@ -99,16 +99,16 @@ private:
     // protocol specific option string
     std::string options_;
 
-    time_t timeout_;
+    std::chrono::seconds timeout_;
 
     Timer registeredTime_;
   public:
     SocketPoolEntry(const std::shared_ptr<SocketCore>& socket,
                     const std::string& option,
-                    time_t timeout);
+                    std::chrono::seconds timeout);
 
     SocketPoolEntry(const std::shared_ptr<SocketCore>& socket,
-                    time_t timeout);
+                    std::chrono::seconds timeout);
 
     ~SocketPoolEntry();
 
@@ -132,10 +132,7 @@ private:
 
   bool noWait_;
 
-  static const int64_t DEFAULT_REFRESH_INTERVAL = 1000;
-
-  // Milliseconds
-  int64_t refreshInterval_;
+  std::chrono::milliseconds refreshInterval_;
   Timer lastRefresh_;
 
   std::unique_ptr<CookieStorage> cookieStorage_;
@@ -272,24 +269,24 @@ public:
                   const std::string& proxyhost, uint16_t proxyport,
                   const std::shared_ptr<SocketCore>& sock,
                   const std::string& options,
-                  time_t timeout = 15);
+                  std::chrono::seconds timeout = std::chrono::seconds(15));
 
   void poolSocket(const std::shared_ptr<Request>& request,
                   const std::string& username,
                   const std::shared_ptr<Request>& proxyRequest,
                   const std::shared_ptr<SocketCore>& socket,
                   const std::string& options,
-                  time_t timeout = 15);
+                  std::chrono::seconds timeout = std::chrono::seconds(15));
 
   void poolSocket(const std::string& ipaddr, uint16_t port,
                   const std::string& proxyhost, uint16_t proxyport,
                   const std::shared_ptr<SocketCore>& sock,
-                  time_t timeout = 15);
+                  std::chrono::seconds timeout = std::chrono::seconds(15));
 
   void poolSocket(const std::shared_ptr<Request>& request,
                   const std::shared_ptr<Request>& proxyRequest,
                   const std::shared_ptr<SocketCore>& socket,
-                  time_t timeout = 15);
+                  std::chrono::seconds timeout = std::chrono::seconds(15));
 
   std::shared_ptr<SocketCore> popPooledSocket
   (const std::string& ipaddr,
@@ -347,7 +344,7 @@ public:
 
   const std::unique_ptr<AuthConfigFactory>& getAuthConfigFactory() const;
 
-  void setRefreshInterval(int64_t interval);
+  void setRefreshInterval(std::chrono::milliseconds interval);
 
   const std::string getSessionId() const
   {

+ 10 - 10
src/DownloadEngineFactory.cc

@@ -166,22 +166,22 @@ DownloadEngineFactory::newDownloadEngine
                         e.get()));
 
   if(op->getAsInt(PREF_AUTO_SAVE_INTERVAL) > 0) {
-    e->addRoutineCommand
-      (make_unique<AutoSaveCommand>(e->newCUID(), e.get(),
-                                    op->getAsInt(PREF_AUTO_SAVE_INTERVAL)));
+    e->addRoutineCommand(make_unique<AutoSaveCommand>(
+        e->newCUID(), e.get(),
+        std::chrono::seconds(op->getAsInt(PREF_AUTO_SAVE_INTERVAL))));
   }
   if(op->getAsInt(PREF_SAVE_SESSION_INTERVAL) > 0) {
-    e->addRoutineCommand(make_unique<SaveSessionCommand>
-                         (e->newCUID(), e.get(),
-                          op->getAsInt(PREF_SAVE_SESSION_INTERVAL)));
+    e->addRoutineCommand(make_unique<SaveSessionCommand>(
+        e->newCUID(), e.get(),
+        std::chrono::seconds(op->getAsInt(PREF_SAVE_SESSION_INTERVAL))));
   }
   e->addRoutineCommand(make_unique<HaveEraseCommand>
-                       (e->newCUID(), e.get(), 10));
+                       (e->newCUID(), e.get(), std::chrono::seconds(10)));
   {
-    time_t stopSec = op->getAsInt(PREF_STOP);
+    auto stopSec = op->getAsInt(PREF_STOP);
     if(stopSec > 0) {
-      e->addRoutineCommand(make_unique<TimedHaltCommand>(e->newCUID(), e.get(),
-                                                         stopSec));
+      e->addRoutineCommand(make_unique<TimedHaltCommand>(
+          e->newCUID(), e.get(), std::chrono::seconds(stopSec)));
     }
   }
   if(op->defined(PREF_STOP_WITH_PROCESS)) {

+ 1 - 2
src/DownloadResult.h

@@ -60,8 +60,7 @@ struct DownloadResult
 
   uint64_t sessionDownloadLength;
 
-  // milliseconds
-  int64_t sessionTime;
+  std::chrono::milliseconds sessionTime;
 
   int64_t totalLength;
 

+ 5 - 4
src/FileAllocationCommand.cc

@@ -71,10 +71,11 @@ bool FileAllocationCommand::executeInternal()
   }
   fileAllocationEntry_->allocateChunk();
   if(fileAllocationEntry_->finished()) {
-    A2_LOG_DEBUG
-      (fmt(MSG_ALLOCATION_COMPLETED,
-           static_cast<long int>(timer_.difference(global::wallclock())),
-           getRequestGroup()->getTotalLength()));
+    A2_LOG_DEBUG(fmt(MSG_ALLOCATION_COMPLETED,
+                     static_cast<long int>(
+                         std::chrono::duration_cast<std::chrono::seconds>(
+                             timer_.difference(global::wallclock())).count()),
+                     getRequestGroup()->getTotalLength()));
     std::vector<std::unique_ptr<Command>> commands;
     fileAllocationEntry_->prepareForNextAction(commands, getDownloadEngine());
     getDownloadEngine()->addCommand(std::move(commands));

+ 5 - 3
src/FileEntry.cc

@@ -72,7 +72,7 @@ FileEntry::FileEntry(std::string path, int64_t length, int64_t offset,
     offset_(offset),
     uris_(uris.begin(), uris.end()),
     path_(std::move(path)),
-    lastFasterReplace_(0),
+    lastFasterReplace_(Timer::zero()),
     maxConnectionPerServer_(1),
     requested_(true),
     uniqueProtocol_(false)
@@ -213,10 +213,13 @@ FileEntry::getRequest
   return req;
 }
 
+namespace {
+constexpr auto startupIdleTime = std::chrono::seconds(10);
+} // namespace
+
 std::shared_ptr<Request>
 FileEntry::findFasterRequest(const std::shared_ptr<Request>& base)
 {
-  const int startupIdleTime = 10;
   if(requestPool_.empty() ||
      lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) {
     return nullptr;
@@ -248,7 +251,6 @@ FileEntry::findFasterRequest
  const std::vector<std::pair<size_t, std::string> >& usedHosts,
  const std::shared_ptr<ServerStatMan>& serverStatMan)
 {
-  const int startupIdleTime = 10;
   const int SPEED_THRESHOLD = 20*1024;
   if(lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) {
     return nullptr;

+ 4 - 2
src/FtpNegotiationCommand.cc

@@ -99,7 +99,8 @@ FtpNegotiationCommand::FtpNegotiationCommand
 {
   ftp_->setBaseWorkingDir(baseWorkingDir);
   if(seq == SEQ_RECV_GREETING) {
-    setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
+    setTimeout(
+        std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)));
   }
   setWriteCheckSocket(getSocket());
 }
@@ -116,7 +117,8 @@ bool FtpNegotiationCommand::executeInternal() {
     auto command = make_unique<FtpDownloadCommand>
       (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), ftp_,
        getDownloadEngine(), dataSocket_, getSocket());
-    command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
+    command->setStartupIdleTime(
+        std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)));
     command->setLowestDownloadSpeedLimit
       (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
     if(getFileEntry()->isUniqueProtocol()) {

+ 6 - 3
src/HaveEraseCommand.cc

@@ -40,8 +40,11 @@
 
 namespace aria2 {
 
-HaveEraseCommand::HaveEraseCommand(cuid_t cuid, DownloadEngine* e, time_t interval)
-  :TimeBasedCommand(cuid, e, interval, true) {}
+HaveEraseCommand::HaveEraseCommand(cuid_t cuid, DownloadEngine* e,
+                                   std::chrono::seconds interval)
+  : TimeBasedCommand(cuid, e, std::move(interval), true)
+{
+}
 
 HaveEraseCommand::~HaveEraseCommand() {}
 
@@ -60,7 +63,7 @@ void HaveEraseCommand::process()
   for(auto & group : groups) {
     const auto& ps = group->getPieceStorage();
     if(ps) {
-      ps->removeAdvertisedPiece(5);
+      ps->removeAdvertisedPiece(std::chrono::seconds(5));
     }
   }
 }

+ 2 - 1
src/HaveEraseCommand.h

@@ -42,7 +42,8 @@ namespace aria2 {
 class HaveEraseCommand : public TimeBasedCommand
 {
 public:
-  HaveEraseCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  HaveEraseCommand(cuid_t cuid, DownloadEngine* e,
+                   std::chrono::seconds interval);
 
   virtual ~HaveEraseCommand();
 

+ 1 - 1
src/HttpRequestCommand.cc

@@ -74,7 +74,7 @@ HttpRequestCommand::HttpRequestCommand
                     httpConnection->getSocketRecvBuffer()),
     httpConnection_(httpConnection)
 {
-  setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
+  setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)));
   disableReadCheckSocket();
   setWriteCheckSocket(getSocket());
 }

+ 2 - 1
src/HttpResponseCommand.cc

@@ -536,7 +536,8 @@ HttpResponseCommand::createHttpDownloadCommand
     (getCuid(), getRequest(), getFileEntry(), getRequestGroup(),
      std::move(httpResponse), httpConnection_, getDownloadEngine(),
      getSocket());
-  command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
+  command->setStartupIdleTime(
+      std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)));
   command->setLowestDownloadSpeedLimit
     (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
   if (getRequestGroup()->isFileAllocationEnabled() &&

+ 4 - 3
src/HttpServerBodyCommand.cc

@@ -148,8 +148,8 @@ void HttpServerBodyCommand::addHttpServerResponseCommand(bool delayed)
   auto resp =
     make_unique<HttpServerResponseCommand>(getCuid(), httpServer_, e_, socket_);
   if (delayed) {
-    e_->addCommand(
-        make_unique<DelayedCommand>(getCuid(), e_, 1, std::move(resp), true));
+    e_->addCommand(make_unique<DelayedCommand>(
+        getCuid(), e_, std::chrono::seconds(1), std::move(resp), true));
     return;
   }
 
@@ -320,7 +320,8 @@ bool HttpServerBodyCommand::execute()
         return false;
       }
     } else {
-      if(timeoutTimer_.difference(global::wallclock()) >= 30) {
+      if(timeoutTimer_.difference(global::wallclock()) >=
+         std::chrono::seconds(30)) {
         A2_LOG_INFO("HTTP request body timeout.");
         return true;
       } else {

+ 2 - 1
src/HttpServerCommand.cc

@@ -253,7 +253,8 @@ bool HttpServerCommand::execute()
         return true;
       }
     } else {
-      if(timeoutTimer_.difference(global::wallclock()) >= 30) {
+      if(timeoutTimer_.difference(global::wallclock()) >=
+         std::chrono::seconds(30)) {
         A2_LOG_INFO("HTTP request timeout.");
         return true;
       } else {

+ 1 - 1
src/InitiateConnectionCommand.cc

@@ -64,7 +64,7 @@ InitiateConnectionCommand::InitiateConnectionCommand
  DownloadEngine* e)
   : AbstractCommand(cuid, req, fileEntry, requestGroup, e)
 {
-  setTimeout(getOption()->getAsInt(PREF_DNS_TIMEOUT));
+  setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_DNS_TIMEOUT)));
   // give a chance to be executed in the next loop in DownloadEngine
   setStatus(Command::STATUS_ONESHOT_REALTIME);
   disableReadCheckSocket();

+ 3 - 2
src/InitiatorMSEHandshakeCommand.cc

@@ -74,7 +74,8 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand
 {
   disableReadCheckSocket();
   setWriteCheckSocket(getSocket());
-  setTimeout(getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
+  setTimeout(std::chrono::seconds(
+      getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)));
 
   btRuntime_->increaseConnections();
   requestGroup_->increaseNumCommand();
@@ -98,7 +99,7 @@ bool InitiatorMSEHandshakeCommand::executeInternal() {
         addCommandSelf();
         return false;
       }
-      setTimeout(getOption()->getAsInt(PREF_BT_TIMEOUT));
+      setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_BT_TIMEOUT)));
       mseHandshake_->initEncryptionFacility(true);
       mseHandshake_->sendPublicKey();
       sequence_ = INITIATOR_SEND_KEY_PENDING;

+ 3 - 3
src/LpdMessageDispatcher.cc

@@ -48,13 +48,13 @@ LpdMessageDispatcher::LpdMessageDispatcher
  uint16_t port,
  const std::string& multicastAddress,
  uint16_t multicastPort,
- time_t interval)
+ std::chrono::seconds interval)
   : infoHash_(infoHash),
     port_(port),
     multicastAddress_(multicastAddress),
     multicastPort_(multicastPort),
-    timer_(0),
-    interval_(interval),
+    timer_(Timer::zero()),
+    interval_(std::move(interval)),
     request_(bittorrent::createLpdRequest(multicastAddress_, multicastPort_,
                                           infoHash_, port_))
 {}

+ 5 - 5
src/LpdMessageDispatcher.h

@@ -52,13 +52,13 @@ private:
   std::string multicastAddress_;
   uint16_t multicastPort_;
   Timer timer_;
-  time_t interval_;
+  std::chrono::seconds interval_;
   std::string request_;
 public:
-  LpdMessageDispatcher
-  (const std::string& infoHash, uint16_t port,
-   const std::string& multicastAddr, uint16_t multicastPort,
-   time_t interval = 5*60);
+  LpdMessageDispatcher(
+      const std::string& infoHash, uint16_t port,
+      const std::string& multicastAddr, uint16_t multicastPort,
+      std::chrono::seconds interval = std::chrono::minutes(5));
 
   ~LpdMessageDispatcher();
 

+ 3 - 7
src/MultiUrlRequestInfo.cc

@@ -135,9 +135,9 @@ std::unique_ptr<StatCalc> getStatCalc(const std::shared_ptr<Option>& op)
   if(op->getAsBool(PREF_QUIET)) {
     return make_unique<NullStatCalc>();
   }
-  auto impl = make_unique<ConsoleStatCalc>(op->getAsInt(PREF_SUMMARY_INTERVAL),
-                                           op->getAsBool(PREF_ENABLE_COLOR),
-                                           op->getAsBool(PREF_HUMAN_READABLE));
+  auto impl = make_unique<ConsoleStatCalc>(
+      std::chrono::seconds(op->getAsInt(PREF_SUMMARY_INTERVAL)),
+      op->getAsBool(PREF_ENABLE_COLOR), op->getAsBool(PREF_HUMAN_READABLE));
   impl->setReadoutVisibility(op->getAsBool(PREF_SHOW_CONSOLE_READOUT));
   impl->setTruncate(op->getAsBool(PREF_TRUNCATE_CONSOLE_READOUT));
   return std::move(impl);
@@ -273,10 +273,6 @@ int MultiUrlRequestInfo::prepare()
       parseAsyncDNSServers(option_->get(PREF_ASYNC_DNS_SERVER));
     e_->setAsyncDNSServers(asyncDNSServers);
 #endif // HAVE_ARES_ADDR_NODE
-    if(!Timer::monotonicClock()) {
-      A2_LOG_WARN("Don't change system time while aria2c is running."
-                  " Doing this may make aria2c hang for long time.");
-    }
 
     std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF);
     if(!serverStatIf.empty()) {

+ 1 - 1
src/Peer.cc

@@ -51,7 +51,7 @@ Peer::Peer(std::string ipaddr, uint16_t port, bool incoming):
   origPort_(port),
   cuid_(0),
   firstContactTime_(global::wallclock()),
-  dropStartTime_(0),
+  dropStartTime_(Timer::zero()),
   seeder_(false),
   incoming_(incoming),
   localPeer_(false),

+ 1 - 1
src/PeerAbstractCommand.cc

@@ -57,7 +57,7 @@ PeerAbstractCommand::PeerAbstractCommand
  : Command(cuid),
    checkPoint_(global::wallclock()),
    // TODO referring global option
-   timeout_(e->getOption()->getAsInt(PREF_BT_TIMEOUT)),
+   timeout_(std::chrono::seconds(e->getOption()->getAsInt(PREF_BT_TIMEOUT))),
    e_(e),
    socket_(s),
    peer_(peer),

+ 6 - 2
src/PeerAbstractCommand.h

@@ -51,7 +51,7 @@ class SocketCore;
 class PeerAbstractCommand : public Command {
 private:
   Timer checkPoint_;
-  time_t timeout_;
+  std::chrono::seconds timeout_;
   DownloadEngine* e_;
   std::shared_ptr<SocketCore> socket_;
   std::shared_ptr<Peer> peer_;
@@ -79,7 +79,11 @@ protected:
     return peer_;
   }
 
-  void setTimeout(time_t timeout) { timeout_ = timeout; }
+  void setTimeout(std::chrono::seconds timeout)
+  {
+    timeout_ = std::move(timeout);
+  }
+
   virtual bool prepareForNextPeer(time_t wait);
   virtual void onAbort() {};
   // This function is called when DownloadFailureException is caught right after

+ 7 - 6
src/PeerInteractionCommand.cc

@@ -102,7 +102,8 @@ PeerInteractionCommand::PeerInteractionCommand
   if(sequence_ == INITIATOR_SEND_HANDSHAKE) {
     disableReadCheckSocket();
     setWriteCheckSocket(getSocket());
-    setTimeout(getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
+    setTimeout(std::chrono::seconds(
+        getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)));
   }
 
   int family;
@@ -180,8 +181,8 @@ PeerInteractionCommand::PeerInteractionCommand
   dispatcher->setCuid(cuid);
   dispatcher->setPeer(getPeer());
   dispatcher->setDownloadContext(requestGroup_->getDownloadContext().get());
-  dispatcher->setRequestTimeout(getOption()->
-                                   getAsInt(PREF_BT_REQUEST_TIMEOUT));
+  dispatcher->setRequestTimeout(
+      std::chrono::seconds(getOption()->getAsInt(PREF_BT_REQUEST_TIMEOUT)));
   dispatcher->setBtMessageFactory(factory.get());
   dispatcher->setRequestGroupMan
     (getDownloadEngine()->getRequestGroupMan().get());
@@ -227,7 +228,7 @@ PeerInteractionCommand::PeerInteractionCommand
     (std::move(extensionMessageFactory));
   btInteractive->setExtensionMessageRegistry(std::move(exMsgRegistry));
   btInteractive->setKeepAliveInterval
-    (getOption()->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL));
+    (std::chrono::seconds(getOption()->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL)));
   btInteractive->setRequestGroupMan
     (getDownloadEngine()->getRequestGroupMan().get());
   btInteractive->setBtMessageFactory(std::move(factory));
@@ -307,7 +308,7 @@ bool PeerInteractionCommand::executeInternal() {
       disableWriteCheckSocket();
       setReadCheckSocket(getSocket());
       //socket->setBlockingMode();
-      setTimeout(getOption()->getAsInt(PREF_BT_TIMEOUT));
+      setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_BT_TIMEOUT)));
       btInteractive_->initiateHandshake();
       sequence_ = INITIATOR_WAIT_HANDSHAKE;
       break;
@@ -403,7 +404,7 @@ void PeerInteractionCommand::onFailure(const Exception& err)
 {
   requestGroup_->setLastErrorCode(err.getErrorCode());
   requestGroup_->setHaltRequested(true);
-  getDownloadEngine()->setRefreshInterval(0);
+  getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
 }
 
 bool PeerInteractionCommand::exitBeforeExecute()

+ 2 - 2
src/PeerSessionResource.cc

@@ -48,8 +48,8 @@ namespace aria2 {
 PeerSessionResource::PeerSessionResource(int32_t pieceLength, int64_t totalLength)
   :
   bitfieldMan_(make_unique<BitfieldMan>(pieceLength, totalLength)),
-  lastDownloadUpdate_(0),
-  lastAmUnchoking_(0),
+  lastDownloadUpdate_(Timer::zero()),
+  lastAmUnchoking_(Timer::zero()),
   dispatcher_(nullptr),
   amChoking_(true),
   amInterested_(false),

+ 1 - 1
src/PieceStorage.h

@@ -254,7 +254,7 @@ public:
    * Removes have entry if specified seconds have elapsed since its
    * registration.
    */
-  virtual void removeAdvertisedPiece(time_t elapsed) = 0;
+  virtual void removeAdvertisedPiece(const std::chrono::seconds& elapsed) = 0;
 
   /**
    * Sets all bits in bitfield to 1.

+ 2 - 1
src/ReceiverMSEHandshakeCommand.cc

@@ -63,7 +63,8 @@ ReceiverMSEHandshakeCommand::ReceiverMSEHandshakeCommand
   sequence_(RECEIVER_IDENTIFY_HANDSHAKE),
   mseHandshake_(make_unique<MSEHandshake>(cuid, s, e->getOption()))
 {
-  setTimeout(e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
+  setTimeout(std::chrono::seconds(
+      e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)));
   mseHandshake_->setWantRead(true);
 }
 

+ 6 - 5
src/RequestGroup.cc

@@ -337,7 +337,7 @@ void RequestGroup::createInitialCommand
     btAnnounce->setPieceStorage(pieceStorage_);
     btAnnounce->setPeerStorage(peerStorage);
     btAnnounce->setUserDefinedInterval
-      (option_->getAsInt(PREF_BT_TRACKER_INTERVAL));
+      (std::chrono::seconds(option_->getAsInt(PREF_BT_TRACKER_INTERVAL)));
     btAnnounce->shuffleAnnounce();
 
     assert(!btRegistry->get(gid_->getNumericId()));
@@ -978,7 +978,7 @@ void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
   peerStorage_ = nullptr;
 #endif // ENABLE_BITTORRENT
   if(pieceStorage_) {
-    pieceStorage_->removeAdvertisedPiece(0);
+    pieceStorage_->removeAdvertisedPiece(std::chrono::seconds(0));
   }
   // Don't reset segmentMan_ and pieceStorage_ here to provide
   // progress information via RPC
@@ -1129,7 +1129,8 @@ std::shared_ptr<DownloadResult> RequestGroup::createDownloadResult() const
   res->fileEntries = downloadContext_->getFileEntries();
   res->inMemoryDownload = inMemoryDownload_;
   res->sessionDownloadLength = st.sessionDownloadLength;
-  res->sessionTime = downloadContext_->calculateSessionTime();
+  res->sessionTime = std::chrono::duration_cast<std::chrono::milliseconds>(
+      downloadContext_->calculateSessionTime());
   res->result = downloadResult();
   res->followedBy = followedByGIDs_;
   res->belongsTo = belongsToGID_;
@@ -1219,9 +1220,9 @@ void RequestGroup::markInMemoryDownload()
   inMemoryDownload_ = true;
 }
 
-void RequestGroup::setTimeout(time_t timeout)
+void RequestGroup::setTimeout(std::chrono::seconds timeout)
 {
-  timeout_ = timeout;
+  timeout_ = std::move(timeout);
 }
 
 bool RequestGroup::doesDownloadSpeedExceed()

+ 3 - 6
src/RequestGroup.h

@@ -136,7 +136,7 @@ private:
   Time lastModifiedTime_;
 
   // Timeout used for HTTP/FTP downloads.
-  time_t timeout_;
+  std::chrono::seconds timeout_;
 
   int state_;
 
@@ -444,12 +444,9 @@ public:
     return inMemoryDownload_;
   }
 
-  void setTimeout(time_t timeout);
+  void setTimeout(std::chrono::seconds timeout);
 
-  time_t getTimeout() const
-  {
-    return timeout_;
-  }
+  const std::chrono::seconds& getTimeout() const { return timeout_; }
 
   // Returns true if current download speed exceeds
   // maxDownloadSpeedLimit_.  Always returns false if

+ 4 - 5
src/RequestGroupMan.cc

@@ -524,7 +524,7 @@ void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
   }
   if(count > 0) {
     e->setNoWait(true);
-    e->setRefreshInterval(0);
+    e->setRefreshInterval(std::chrono::milliseconds(0));
     A2_LOG_DEBUG(fmt("%d RequestGroup(s) added.", count));
   }
 }
@@ -704,10 +704,9 @@ void formatDownloadResultCommon
   o << std::setw(3) << downloadResult->gid->toAbbrevHex() << "|"
     << std::setw(4) << status << "|"
     << std::setw(11);
-  if(downloadResult->sessionTime > 0) {
-    o << util::abbrevSize
-      (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
-      "B/s";
+  if(downloadResult->sessionTime.count() > 0) {
+    o << util::abbrevSize(downloadResult->sessionDownloadLength * 1000 /
+                          downloadResult->sessionTime.count()) << "B/s";
   } else {
     o << "n/a";
   }

+ 3 - 6
src/RequestSlot.cc

@@ -36,12 +36,9 @@
 
 namespace aria2 {
 
-void RequestSlot::setDispatchedTime(time_t sec) {
-  dispatchedTime_.reset(sec);
-}
-
-bool RequestSlot::isTimeout(time_t timeoutSec) const {
-  return dispatchedTime_.difference(global::wallclock()) >= timeoutSec;
+bool RequestSlot::isTimeout(const std::chrono::seconds& t) const
+{
+  return dispatchedTime_.difference(global::wallclock()) >= t;
 }
 
 } // namespace aria2

+ 11 - 5
src/RequestSlot.h

@@ -51,8 +51,12 @@ public:
       piece_(std::move(piece))
   {}
 
-  RequestSlot():dispatchedTime_(0), index_(0), begin_(0), length_(0),
-                blockIndex_(0)
+  RequestSlot()
+    : dispatchedTime_(Timer::zero()),
+      index_(0),
+      begin_(0),
+      length_(0),
+      blockIndex_(0)
   {}
 
   bool operator==(const RequestSlot& requestSlot) const
@@ -75,9 +79,7 @@ public:
     }
   }
 
-  void setDispatchedTime(time_t secFromEpoch);
-
-  bool isTimeout(time_t timeoutSec) const;
+  bool isTimeout(const std::chrono::seconds& t) const;
 
   size_t getIndex() const { return index_; }
   void setIndex(size_t index) { index_ = index; }
@@ -95,6 +97,10 @@ public:
   {
     return piece_;
   }
+
+  // For unit test
+  void setDispatchedTime(Timer t) { dispatchedTime_ = std::move(t); }
+
 private:
   Timer dispatchedTime_;
   size_t index_;

+ 4 - 4
src/RpcMethodImpl.cc

@@ -391,7 +391,7 @@ std::unique_ptr<ValueBase> removeDownload
       } else {
         group->setHaltRequested(true, RequestGroup::USER_REQUEST);
       }
-      e->setRefreshInterval(0);
+      e->setRefreshInterval(std::chrono::milliseconds(0));
     } else {
       if(group->isDependencyResolved()) {
         e->getRequestGroupMan()->removeReservedGroup(gid);
@@ -431,7 +431,7 @@ std::unique_ptr<ValueBase> pauseDownload
   if(group) {
     bool reserved = group->getState() == RequestGroup::STATE_WAITING;
     if(pauseRequestGroup(group, reserved, forcePause)) {
-      e->setRefreshInterval(0);
+      e->setRefreshInterval(std::chrono::milliseconds(0));
       return createGIDResponse(gid);
     }
   }
@@ -1306,8 +1306,8 @@ std::unique_ptr<ValueBase> goingShutdown
 {
   // Schedule shutdown after 3seconds to give time to client to
   // receive RPC response.
-  e->addRoutineCommand(make_unique<TimedHaltCommand>
-                       (e->newCUID(), e, 3, forceHalt));
+  e->addRoutineCommand(make_unique<TimedHaltCommand>(
+      e->newCUID(), e, std::chrono::seconds(3), forceHalt));
   A2_LOG_INFO("Scheduled shutdown in 3 seconds.");
   return createOKResponse();
 }

+ 2 - 2
src/SaveSessionCommand.cc

@@ -44,8 +44,8 @@
 namespace aria2 {
 
 SaveSessionCommand::SaveSessionCommand
-(cuid_t cuid, DownloadEngine* e, time_t interval)
-  : TimeBasedCommand(cuid, e, interval, true)
+(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval)
+  : TimeBasedCommand(cuid, e, std::move(interval), true)
 {}
 
 SaveSessionCommand::~SaveSessionCommand() {}

+ 2 - 1
src/SaveSessionCommand.h

@@ -42,7 +42,8 @@ namespace aria2 {
 class SaveSessionCommand : public TimeBasedCommand
 {
 public:
-  SaveSessionCommand(cuid_t cuid, DownloadEngine* e, time_t interval);
+  SaveSessionCommand(cuid_t cuid, DownloadEngine* e,
+                     std::chrono::seconds interval);
 
   virtual ~SaveSessionCommand();
 

+ 1 - 1
src/SftpNegotiationCommand.cc

@@ -168,7 +168,7 @@ bool SftpNegotiationCommand::executeInternal() {
         (getCuid(), getRequest(), getFileEntry(), getRequestGroup(),
          getDownloadEngine(), getSocket(), std::move(authConfig_));
       command->setStartupIdleTime
-        (getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
+        (std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)));
       command->setLowestDownloadSpeedLimit
         (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
       command->setStatus(Command::STATUS_ONESHOT_REALTIME);

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác