deferred_sequenced_task_runner.h 2.6 KB
Newer Older
1 2 3 4
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#ifndef BASE_DEFERRED_SEQUENCED_TASK_RUNNER_H_
#define BASE_DEFERRED_SEQUENCED_TASK_RUNNER_H_
7 8 9 10 11 12

#include <vector>

#include "base/base_export.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
13
#include "base/macros.h"
14
#include "base/memory/ref_counted.h"
15
#include "base/sequenced_task_runner.h"
16
#include "base/synchronization/lock.h"
17
#include "base/time/time.h"
18 19 20 21 22 23 24 25 26
#include "base/tracked_objects.h"

namespace base {

// A DeferredSequencedTaskRunner is a subclass of SequencedTaskRunner that
// queues up all requests until the first call to Start() is issued.
class BASE_EXPORT DeferredSequencedTaskRunner : public SequencedTaskRunner {
 public:
  explicit DeferredSequencedTaskRunner(
27
      scoped_refptr<SequencedTaskRunner> target_runner);
28 29

  // TaskRunner implementation
30
  bool PostDelayedTask(const tracked_objects::Location& from_here,
31
                       OnceClosure task,
32 33
                       TimeDelta delay) override;
  bool RunsTasksOnCurrentThread() const override;
34 35

  // SequencedTaskRunner implementation
36
  bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
37
                                  OnceClosure task,
38
                                  TimeDelta delay) override;
39 40 41 42 43 44 45 46 47 48

  // Start the execution - posts all queued tasks to the target executor. The
  // deferred tasks are posted with their initial delay, meaning that the task
  // execution delay is actually measured from Start.
  // Fails when called a second time.
  void Start();

 private:
  struct DeferredTask  {
    DeferredTask();
49
    DeferredTask(DeferredTask&& other);
50
    ~DeferredTask();
51
    DeferredTask& operator=(DeferredTask&& other);
52 53

    tracked_objects::Location posted_from;
54
    OnceClosure task;
55 56 57 58 59
    // The delay this task was initially posted with.
    TimeDelta delay;
    bool is_non_nestable;
  };

60
  ~DeferredSequencedTaskRunner() override;
61 62 63

  // Creates a |Task| object and adds it to |deferred_tasks_queue_|.
  void QueueDeferredTask(const tracked_objects::Location& from_here,
64
                         OnceClosure task,
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
                         TimeDelta delay,
                         bool is_non_nestable);

  // // Protects |started_| and |deferred_tasks_queue_|.
  mutable Lock lock_;

  bool started_;
  const scoped_refptr<SequencedTaskRunner> target_task_runner_;
  std::vector<DeferredTask> deferred_tasks_queue_;

  DISALLOW_COPY_AND_ASSIGN(DeferredSequencedTaskRunner);
};

}  // namespace base

80
#endif  // BASE_DEFERRED_SEQUENCED_TASK_RUNNER_H_