• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H
17 #define OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H
18 
19 #include <atomic>
20 #include <chrono>
21 #include <condition_variable>
22 #include <functional>
23 #include <map>
24 #include <memory>
25 #include <string>
26 #include <thread>
27 #include <unordered_map>
28 
29 #include "logging.h"
30 #include "nocopyable.h"
31 
32 class ScheduleTaskManager {
33 public:
34     static ScheduleTaskManager& GetInstance();
35 
36     using ms = std::chrono::milliseconds;
37 
38     bool ScheduleTask(const std::string& name,
39                       const std::function<void(void)>& callback,
40                       const std::chrono::milliseconds& repeatInterval);
41 
42     bool ScheduleTask(const std::string& name,
43                       const std::function<void(void)>& callback,
44                       const std::chrono::milliseconds& repeatInterval,
45                       std::chrono::milliseconds initialDelay);
46 
47     bool UnscheduleTask(const std::string& name);
48 
49     void Shutdown();
50 
51     ScheduleTaskManager();
52     ~ScheduleTaskManager();
53 
54 private:
55     using Clock = std::chrono::steady_clock;
56     using TimePoint = std::chrono::time_point<Clock>;
57 
58     struct Task {
59         std::string name;
60         std::function<void(void)> callback;
61         std::chrono::milliseconds repeatInterval;
62         std::chrono::milliseconds initialDelay;
63         TimePoint nextRunTime;
64     };
65     using SharedTask = STD_PTR(shared, Task);
66     using WeakTask = STD_PTR(weak, Task);
67 
68     static std::chrono::milliseconds NormalizeInterval(std::chrono::milliseconds interval);
69 
70     void DumpTask(const SharedTask& task);
71 
72     void ScheduleThread();
73 
74     WeakTask TakeFront();
75 
76 private:
77     mutable std::mutex taskMutex_;
78     std::condition_variable taskCv_;
79     std::atomic<bool> runScheduleThread_ = true;
80     std::multimap<TimePoint, WeakTask> timeMap_;          // schedule list
81     std::unordered_map<std::string, SharedTask> taskMap_; // task details
82     std::thread scheduleThread_;
83 
84     DISALLOW_COPY_AND_MOVE(ScheduleTaskManager);
85 };
86 
87 #endif // !OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H