• 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 #include "serial_queue.h"
17 
18 #include <limits>
19 
20 #include "app_log_wrapper.h"
21 
22 namespace OHOS {
23 namespace AppExecFwk {
24 using namespace ffrt;
25 namespace {
26 constexpr uint32_t CONVERSION_FACTOR = 1000; // ms to us
27 }
28 
SerialQueue(const std::string & queueName)29 SerialQueue::SerialQueue(const std::string &queueName)
30 {
31     APP_LOGD("create SerialQueue, queueName : %{public}s", queueName.c_str());
32     queue_ = std::make_shared<queue>(queueName.c_str());
33 }
34 
~SerialQueue()35 SerialQueue::~SerialQueue()
36 {
37     APP_LOGD("destroy SerialQueue");
38 }
39 
ScheduleDelayTask(const std::string & taskName,uint64_t ms,std::function<void ()> func)40 void SerialQueue::ScheduleDelayTask(const std::string &taskName, uint64_t ms, std::function<void()> func)
41 {
42     APP_LOGD("begin to ScheduleDelayTask, taskName : %{public}s", taskName.c_str());
43     if (ms > std::numeric_limits<uint64_t>::max() / CONVERSION_FACTOR) {
44         APP_LOGE("invalid ms, ScheduleDelayTask failed");
45         return;
46     }
47     std::unique_lock<std::shared_mutex> lock(mutex_);
48     task_handle task_handle = queue_->submit_h(func, task_attr().delay(ms * CONVERSION_FACTOR));
49     if (task_handle == nullptr) {
50         APP_LOGE("submit_h return null, ScheduleDelayTask failed");
51         return;
52     }
53     taskMap_[taskName] = std::move(task_handle);
54     APP_LOGD("ScheduleDelayTask success");
55 }
56 
CancelDelayTask(const std::string & taskName)57 void SerialQueue::CancelDelayTask(const std::string &taskName)
58 {
59     APP_LOGD("begin to CancelDelayTask, taskName : %{public}s", taskName.c_str());
60     std::unique_lock<std::shared_mutex> lock(mutex_);
61     auto item = taskMap_.find(taskName);
62     if (item == taskMap_.end()) {
63         APP_LOGW("task not found, CancelDelayTask failed");
64         return;
65     }
66     if (item->second != nullptr) {
67         int32_t ret = queue_->cancel(item->second);
68         if (ret != 0) {
69             APP_LOGW("CancelDelayTask failed, error code : %{public}d", ret);
70         }
71     }
72     taskMap_.erase(taskName);
73     APP_LOGD("CancelDelayTask success");
74 }
75 }  // namespace AppExecFwk
76 }  // namespace OHOS
77