• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "cast_timer.h"
16 #include "cast_engine_log.h"
17 
18 namespace OHOS {
19 namespace CastEngine {
20 namespace CastEngineService {
21 DEFINE_CAST_ENGINE_LABEL("Cast-Timer");
22 
~CastTimer()23 CastTimer::~CastTimer()
24 {
25     CLOGD("%s In, exit_ = %d.", __FUNCTION__, exit_.load());
26     if (exit_.load()) {
27         return;
28     }
29     Stop();
30 }
31 
Start(std::function<void ()> task,int interval)32 void CastTimer::Start(std::function<void()> task, int interval)
33 {
34     CLOGD("%s In, exit_ = %d.", __FUNCTION__, exit_.load());
35     std::unique_lock<std::mutex> locker(threadMutex_);
36     exit_ = false;
37     workThread_ = std::thread([this, interval, task]() {
38         while (!exit_.load()) {
39             {
40                 // sleep every interval and do the task again and again until times up
41                 std::unique_lock<std::mutex> locker(mutex_);
42                 cond_.wait_for(locker, std::chrono::milliseconds(interval), [this] { return exit_.load(); });
43             }
44 
45             if (exit_.load()) {
46                 return;
47             }
48 
49             if (task) {
50                 task();
51             }
52         }
53     });
54 }
55 
Stop()56 void CastTimer::Stop()
57 {
58     CLOGD("%s In, exit_ = %d.", __FUNCTION__, exit_.load());
59     std::unique_lock<std::mutex> locker(threadMutex_);
60     exit_ = true;
61     {
62         std::unique_lock<std::mutex> locker(mutex_);
63         cond_.notify_all();
64     }
65     if (workThread_.joinable()) {
66         workThread_.join();
67     }
68 }
69 
IsStopped()70 bool CastTimer::IsStopped()
71 {
72     return exit_;
73 }
74 } // namespace CastEngineService
75 } // namespace CastEngine
76 } // namespace OHOS