1 /* 2 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development 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_SHARING_TIMEOUT_TIMER_CPP 17 #define OHOS_SHARING_TIMEOUT_TIMER_CPP 18 19 #include <functional> 20 #include <future> 21 #include <memory> 22 #include <thread> 23 #include <utility> 24 25 namespace OHOS { 26 namespace Sharing { 27 class TimeoutTimer { 28 public: 29 explicit TimeoutTimer(std::string info = "TimeoutTimer"); 30 ~TimeoutTimer(); 31 32 void StopTimer(); 33 void SetTimeoutCallback(std::function<void()> callback); 34 void StartTimer(int timeout, std::string info = "none", std::function<void()> callback = nullptr, 35 bool reuse = false); 36 37 private: 38 void MainLoop(); 39 40 private: 41 enum State { INIT, WAITING, WORKING, CANCELLED, EXITED }; 42 43 bool reuse_ = false; 44 45 int timeout_ = 0; 46 47 std::string taskName_; 48 std::mutex taskMutex_; 49 std::mutex waitMutex_; 50 std::mutex cancelMutex_; 51 std::mutex operateMutex_; 52 std::function<void()> callback_; 53 std::condition_variable taskSignal_; 54 std::condition_variable waitSignal_; 55 std::condition_variable cancelSignal_; 56 std::unique_ptr<std::thread> thread_; 57 58 State state_ = INIT; 59 }; 60 } // namespace Sharing 61 } // namespace OHOS 62 #endif // OHOS_SHARING_TIMEOUT_TIMER_CPP