1 // Copyright 2016 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 #ifndef BASE_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_ 6 #define BASE_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_ 7 8 #include <memory> 9 #include <utility> 10 #include <vector> 11 12 #include "base/base_export.h" 13 #include "base/callback.h" 14 #include "base/macros.h" 15 #include "base/memory/ptr_util.h" 16 #include "base/memory/ref_counted.h" 17 #include "base/synchronization/atomic_flag.h" 18 #include "base/task_scheduler/scheduler_lock.h" 19 #include "base/time/default_tick_clock.h" 20 #include "base/time/tick_clock.h" 21 22 namespace base { 23 24 class TaskRunner; 25 26 namespace internal { 27 28 struct Task; 29 30 // The DelayedTaskManager forwards tasks to post task callbacks when they become 31 // ripe for execution. Tasks are not forwarded before Start() is called. This 32 // class is thread-safe. 33 class BASE_EXPORT DelayedTaskManager { 34 public: 35 // Posts |task| for execution immediately. 36 using PostTaskNowCallback = OnceCallback<void(Task task)>; 37 38 // |tick_clock| can be specified for testing. 39 DelayedTaskManager(std::unique_ptr<const TickClock> tick_clock = 40 std::make_unique<DefaultTickClock>()); 41 ~DelayedTaskManager(); 42 43 // Starts the delayed task manager, allowing past and future tasks to be 44 // forwarded to their callbacks as they become ripe for execution. 45 // |service_thread_task_runner| posts tasks to the TaskScheduler service 46 // thread. 47 void Start(scoped_refptr<TaskRunner> service_thread_task_runner); 48 49 // Schedules a call to |post_task_now_callback| with |task| as argument when 50 // |task| is ripe for execution and Start() has been called. 51 void AddDelayedTask(Task task, PostTaskNowCallback post_task_now_callback); 52 53 private: 54 // Schedules a call to |post_task_now_callback| with |task| as argument when 55 // |delay| expires. Start() must have been called before this. 56 void AddDelayedTaskNow(Task task, 57 TimeDelta delay, 58 PostTaskNowCallback post_task_now_callback); 59 60 const std::unique_ptr<const TickClock> tick_clock_; 61 62 AtomicFlag started_; 63 64 // Synchronizes access to all members below before |started_| is set. Once 65 // |started_| is set: 66 // - |service_thread_task_runner| doest not change, so it can be read without 67 // holding the lock. 68 // - |tasks_added_before_start_| isn't accessed anymore. 69 SchedulerLock lock_; 70 71 scoped_refptr<TaskRunner> service_thread_task_runner_; 72 std::vector<std::pair<Task, PostTaskNowCallback>> tasks_added_before_start_; 73 74 DISALLOW_COPY_AND_ASSIGN(DelayedTaskManager); 75 }; 76 77 } // namespace internal 78 } // namespace base 79 80 #endif // BASE_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_ 81