1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/metrics/metrics_scheduler.h"
6
7 #include "build/build_config.h"
8
9 namespace metrics {
10 namespace {
11
12 // The delay, in seconds, after startup before sending the first log message.
13 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
14 // Sessions are more likely to be short on a mobile device, so handle the
15 // initial log quickly.
16 const int kInitialIntervalSeconds = 15;
17 #else
18 const int kInitialIntervalSeconds = 60;
19 #endif
20
21 } // namespace
22
MetricsScheduler(const base::RepeatingClosure & task_callback,bool fast_startup_for_testing)23 MetricsScheduler::MetricsScheduler(const base::RepeatingClosure& task_callback,
24 bool fast_startup_for_testing)
25 : task_callback_(task_callback),
26 interval_(base::Seconds(
27 fast_startup_for_testing ? 0 : kInitialIntervalSeconds)),
28 running_(false),
29 callback_pending_(false) {}
30
~MetricsScheduler()31 MetricsScheduler::~MetricsScheduler() {}
32
Start()33 void MetricsScheduler::Start() {
34 running_ = true;
35 ScheduleNextTask();
36 }
37
Stop()38 void MetricsScheduler::Stop() {
39 running_ = false;
40 if (timer_.IsRunning())
41 timer_.Stop();
42 }
43
44 // static
GetInitialIntervalSeconds()45 int MetricsScheduler::GetInitialIntervalSeconds() {
46 return kInitialIntervalSeconds;
47 }
48
TaskDone(base::TimeDelta next_interval)49 void MetricsScheduler::TaskDone(base::TimeDelta next_interval) {
50 DCHECK(callback_pending_);
51 callback_pending_ = false;
52 interval_ = next_interval;
53 if (running_)
54 ScheduleNextTask();
55 }
56
TriggerTask()57 void MetricsScheduler::TriggerTask() {
58 // This can happen in tests which set a very small timer interval.
59 if (callback_pending_)
60 return;
61
62 callback_pending_ = true;
63 task_callback_.Run();
64 }
65
ScheduleNextTask()66 void MetricsScheduler::ScheduleNextTask() {
67 DCHECK(running_);
68 if (timer_.IsRunning() || callback_pending_)
69 return;
70
71 timer_.Start(FROM_HERE, interval_, this, &MetricsScheduler::TriggerTask);
72 }
73
74 } // namespace metrics
75