1// Copyright (c) 2013 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
5#include "chrome/browser/metrics/variations/variations_request_scheduler_mobile.h"
6
7#include "base/prefs/pref_service.h"
8#include "chrome/common/pref_names.h"
9
10namespace chrome_variations {
11
12namespace {
13
14// Time before attempting a seed fetch after a ScheduleFetch(), in seconds.
15const int kScheduleFetchDelaySeconds = 5;
16
17// Time between seed fetches, in hours.
18const int kSeedFetchPeriodHours = 5;
19
20}  // namespace
21
22VariationsRequestSchedulerMobile::VariationsRequestSchedulerMobile(
23    const base::Closure& task,
24    PrefService* local_state) :
25  VariationsRequestScheduler(task), local_state_(local_state) {
26}
27
28VariationsRequestSchedulerMobile::~VariationsRequestSchedulerMobile() {
29}
30
31void VariationsRequestSchedulerMobile::Start() {
32  // Check the time of the last request. If it has been longer than the fetch
33  // period, run the task. Otherwise, do nothing. Note that no future requests
34  // are scheduled since it is unlikely that the mobile process would live long
35  // enough for the timer to fire.
36  const base::Time last_fetch_time = base::Time::FromInternalValue(
37      local_state_->GetInt64(prefs::kVariationsLastFetchTime));
38  if (base::Time::Now() >
39      last_fetch_time + base::TimeDelta::FromHours(kSeedFetchPeriodHours)) {
40    last_request_time_ = base::Time::Now();
41    task().Run();
42  }
43}
44
45void VariationsRequestSchedulerMobile::Reset() {
46}
47
48void VariationsRequestSchedulerMobile::OnAppEnterForeground() {
49  // Verify we haven't just attempted a fetch (which has not completed). This
50  // is mainly used to verify we don't trigger a second fetch for the
51  // OnAppEnterForeground right after startup.
52  if (base::Time::Now() <
53      last_request_time_ + base::TimeDelta::FromHours(kSeedFetchPeriodHours)) {
54    return;
55  }
56
57  // Since Start() launches a one-off execution, we can reuse it here. Also
58  // note that since Start() verifies that the seed needs to be refreshed, we
59  // do not verify here.
60  schedule_fetch_timer_.Start(
61      FROM_HERE,
62      base::TimeDelta::FromSeconds(kScheduleFetchDelaySeconds),
63      this,
64      &VariationsRequestSchedulerMobile::Start);
65}
66
67// static
68VariationsRequestScheduler* VariationsRequestScheduler::Create(
69    const base::Closure& task,
70    PrefService* local_state) {
71  return new VariationsRequestSchedulerMobile(task, local_state);
72}
73
74}  // namespace chrome_variations
75