1 /*
2  * Copyright (c) 2023-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 #ifndef OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_H
17 #define OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_H
18 
19 #include <cstdint>
20 #include <functional>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 
25 namespace OHOS {
26 namespace CameraStandard {
27 namespace DeferredProcessing {
28 using TimerCallback = std::function<void()>;
29 
30 enum class TimerType {
31     ONCE = 0,
32     PERIODIC = 1
33 };
34 
35 class TimerCore;
36 
37 class Timer : public std::enable_shared_from_this<Timer> {
38 public:
39     static std::shared_ptr<Timer> Create(const std::string& name, TimerType timerType,
40         uint32_t intervalMs, TimerCallback callback);
41     ~Timer();
42     const std::string& GetName();
43     bool Start(uint32_t delayTimeMs = 0);
44     bool StartAt(uint64_t timestampMs);
45     bool Stop();
46     bool IsActive();
47 
48 private:
49     friend TimerCore;
50     Timer(const std::string& name, TimerType timerType, uint32_t intervalMs, TimerCallback callback);
51     bool Initialize();
52     bool StartUnlocked(uint32_t delayTimeMs = 0);
53     bool StartAtUnlocked(uint64_t timestampMs);
54     void TimerExpired();
55 
56     std::mutex mutex_;
57     bool active_{false};
58     const std::string name_;
59     const TimerType timerType_;
60     const uint32_t intervalMs_;
61     TimerCallback callback_;
62     uint64_t expiredTimeMs_{0};
63 };
64 } //namespace DeferredProcessing
65 } // namespace CameraStandard
66 } // namespace OHOS
67 #endif // OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_H