backoff_timer.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/host/backoff_timer.h"
  5. #include <memory>
  6. #include <utility>
  7. #include "base/bind.h"
  8. namespace remoting {
  9. BackoffTimer::BackoffTimer() = default;
  10. BackoffTimer::~BackoffTimer() = default;
  11. void BackoffTimer::Start(const base::Location& posted_from,
  12. base::TimeDelta delay,
  13. base::TimeDelta max_delay,
  14. const base::RepeatingClosure& user_task) {
  15. backoff_policy_.multiply_factor = 2;
  16. backoff_policy_.initial_delay_ms = delay.InMilliseconds();
  17. backoff_policy_.maximum_backoff_ms = max_delay.InMilliseconds();
  18. backoff_policy_.entry_lifetime_ms = -1;
  19. backoff_entry_ = std::make_unique<net::BackoffEntry>(&backoff_policy_);
  20. posted_from_ = posted_from;
  21. user_task_ = user_task;
  22. StartTimer();
  23. }
  24. void BackoffTimer::Stop() {
  25. timer_.Stop();
  26. user_task_.Reset();
  27. backoff_entry_.reset();
  28. }
  29. void BackoffTimer::StartTimer() {
  30. timer_.Start(
  31. posted_from_, backoff_entry_->GetTimeUntilRelease(),
  32. base::BindOnce(&BackoffTimer::OnTimerFired, base::Unretained(this)));
  33. }
  34. void BackoffTimer::OnTimerFired() {
  35. DCHECK(IsRunning());
  36. DCHECK(!user_task_.is_null());
  37. backoff_entry_->InformOfRequest(false);
  38. StartTimer();
  39. // Running the user task may destroy this object, so don't reference
  40. // any fields of this object after running it.
  41. base::RepeatingClosure user_task(user_task_);
  42. user_task.Run();
  43. }
  44. } // namespace remoting