1 // Copyright 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.
5 #include "storage/browser/fileapi/timed_task_helper.h"
8 #include "base/logging.h"
9 #include "base/sequenced_task_runner.h"
13 struct TimedTaskHelper::Tracker
{
14 explicit Tracker(TimedTaskHelper
* timer
) : timer(timer
) {}
18 timer
->tracker_
= NULL
;
21 TimedTaskHelper
* timer
;
24 TimedTaskHelper::TimedTaskHelper(base::SequencedTaskRunner
* task_runner
)
25 : task_runner_(task_runner
),
29 TimedTaskHelper::~TimedTaskHelper() {
31 tracker_
->timer
= NULL
;
34 bool TimedTaskHelper::IsRunning() const {
35 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
36 return tracker_
!= NULL
;
39 void TimedTaskHelper::Start(
40 const tracked_objects::Location
& posted_from
,
41 base::TimeDelta delay
,
42 const base::Closure
& user_task
) {
43 posted_from_
= posted_from
;
45 user_task_
= user_task
;
49 void TimedTaskHelper::Reset() {
50 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
51 DCHECK(!user_task_
.is_null());
52 desired_run_time_
= base::TimeTicks::Now() + delay_
;
57 // Initialize the tracker for the first time.
58 tracker_
= new Tracker(this);
59 PostDelayedTask(make_scoped_ptr(tracker_
), delay_
);
63 void TimedTaskHelper::Fired(scoped_ptr
<Tracker
> tracker
) {
66 TimedTaskHelper
* timer
= tracker
->timer
;
67 timer
->OnFired(tracker
.Pass());
70 void TimedTaskHelper::OnFired(scoped_ptr
<Tracker
> tracker
) {
71 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
72 base::TimeTicks now
= base::TimeTicks::Now();
73 if (desired_run_time_
> now
) {
74 PostDelayedTask(tracker
.Pass(), desired_run_time_
- now
);
78 base::Closure task
= user_task_
;
83 void TimedTaskHelper::PostDelayedTask(scoped_ptr
<Tracker
> tracker
,
84 base::TimeDelta delay
) {
85 task_runner_
->PostDelayedTask(
87 base::Bind(&TimedTaskHelper::Fired
, base::Passed(&tracker
)),
91 } // namespace storage