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