1 /*
2  * Copyright (c) 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 "ffrt_timer.h"
17 
18 #include "cloud_file_log.h"
19 
20 namespace OHOS::FileManagement::CloudFile {
21 static constexpr uint32_t TIMER_MAX_INTERVAL_MS = 200;
22 using namespace std;
23 
FfrtTimer(const std::string & name)24 FfrtTimer::FfrtTimer(const std::string &name) : name_(name) {}
25 
~FfrtTimer()26 FfrtTimer ::~FfrtTimer()
27 {
28     Stop();
29 }
30 
Start(const TimerCallback & callback,uint32_t interval,uint32_t repatTimes)31 void FfrtTimer::Start(const TimerCallback &callback, uint32_t interval, uint32_t repatTimes)
32 {
33     unique_lock<ffrt::mutex> lock(taskMutex_);
34     if (running_ == true) {
35         LOGE("timer may be is running, timerName:%{public}s", name_.c_str());
36         return;
37     }
38     LOGD("start timer, timerName:%{public}s", name_.c_str());
39     running_ = true;
40     auto task = [this, interval, callback, repatTimes]() {
41         LOGD("task entering loop");
42         uint32_t times = repatTimes;
43         while (times > 0) {
44             callback();
45             times--;
46             unique_lock<ffrt::mutex> lock(sleepMutex_);
47             bool stop =
48                 sleepCv_.wait_for(lock, std::chrono::milliseconds(interval), [this]() { return !this->running_; });
49             if (stop) { // is stopped
50                 break;
51             }
52         }
53         LOGD("task leaving loop");
54     };
55 
56     isJoinable_ = std::make_unique<bool>(true);
57     ffrt::submit(task, {}, {isJoinable_.get()}, ffrt::task_attr().name(name_.c_str()));
58 }
59 
Stop()60 void FfrtTimer::Stop()
61 {
62     unique_lock<ffrt::mutex> lock(taskMutex_);
63     if (running_ == false) {
64         LOGE("timer may be is stopped, timerName:%{public}s", name_.c_str());
65         return;
66     }
67 
68     LOGD("stop timer, timerName:%{public}s", name_.c_str());
69     {
70         std::unique_lock<ffrt::mutex> lock(sleepMutex_);
71         running_ = false;
72         sleepCv_.notify_one();
73     }
74 
75     if (isJoinable_.get() && *isJoinable_) {
76         ffrt::wait({isJoinable_.get()});
77         *isJoinable_ = false;
78     }
79     LOGD("timer is stoped, timerName:%{public}s", name_.c_str());
80 }
81 } // namespace OHOS::FileManagement::CloudFile