• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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_ROSEN_WINDOW_SCENE_TASK_SCHEDULER_H
17 #define OHOS_ROSEN_WINDOW_SCENE_TASK_SCHEDULER_H
18 
19 #include <event_handler.h>
20 
21 namespace OHOS::Rosen {
22 
23 void StartTraceForSyncTask(std::string name);
24 void FinishTraceForSyncTask();
25 
26 class TaskScheduler {
27 public:
28     explicit TaskScheduler(const std::string& threadName);
29     ~TaskScheduler() = default;
30 
31     std::shared_ptr<AppExecFwk::EventHandler> GetEventHandler();
32     using Task = std::function<void()>;
33     void PostAsyncTask(Task&& task, const std::string& name = "ssmTask", int64_t delayTime = 0);
34     void PostVoidSyncTask(Task&& task, const std::string& name = "ssmTask");
35     void PostTask(Task&& task, const std::string& name, int64_t delayTime = 0);
36     void RemoveTask(const std::string& name);
37     template<typename SyncTask, typename Return = std::invoke_result_t<SyncTask>>
38     Return PostSyncTask(SyncTask&& task, const std::string& name = "ssmTask")
39     {
40         Return ret;
41         if (!handler_ || handler_->GetEventRunner()->IsCurrentRunnerThread()) {
42             StartTraceForSyncTask(name);
43             ret = task();
44             FinishTraceForSyncTask();
45             return ret;
46         }
47         auto syncTask = [&ret, &task, name]() {
48             StartTraceForSyncTask(name);
49             ret = task();
50             FinishTraceForSyncTask();
51         };
52         handler_->PostSyncTask(std::move(syncTask), "wms:" + name, AppExecFwk::EventQueue::Priority::IMMEDIATE);
53         return ret;
54     }
55 
56 private:
57     std::shared_ptr<AppExecFwk::EventHandler> handler_;
58 };
59 } // namespace OHOS::Rosen
60 #endif // OHOS_ROSEN_WINDOW_SCENE_TASK_SCHEDULER_H
61