1/*
2 * Copyright (c) 2022 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 "utils_timer.h"
17
18#include <functional>
19#include <new>
20
21#include "nocopyable.h"
22#include "singleton.h"
23#include "timer.h"
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
29namespace {
30using namespace OHOS;
31class UtilsTimer final : public OHOS::Utils::Timer, public DelayedRefSingleton<UtilsTimer> {
32public:
33    UtilsTimer();
34    ~UtilsTimer() override;
35};
36
37UtilsTimer::~UtilsTimer()
38{
39    this->Shutdown();
40}
41
42UtilsTimer::UtilsTimer() : Timer("timer_process")
43{
44    this->Setup();
45}
46} // namespace
47
48void DoTimerProcess(TimerProc callback, const void *context)
49{
50    if (callback != nullptr) {
51        callback(context);
52    }
53}
54
55TimerHandle DslmUtilsStartPeriodicTimerTask(uint32_t interval, TimerProc callback, const void *context)
56{
57    UtilsTimer &st = DelayedRefSingleton<UtilsTimer>::GetInstance();
58    uint32_t timerId = st.Register([callback, context]() { DoTimerProcess(callback, context); }, interval, false);
59    return static_cast<TimerHandle>(timerId);
60}
61
62TimerHandle DslmUtilsStartOnceTimerTask(uint32_t interval, TimerProc callback, const void *context)
63{
64    UtilsTimer &st = DelayedRefSingleton<UtilsTimer>::GetInstance();
65    uint32_t timerId = st.Register([callback, context]() { DoTimerProcess(callback, context); }, interval, true);
66    return static_cast<TimerHandle>(timerId);
67}
68
69void DslmUtilsStopTimerTask(TimerHandle handle)
70{
71    UtilsTimer &st = DelayedRefSingleton<UtilsTimer>::GetInstance();
72    st.Unregister(static_cast<uint32_t>(handle));
73}
74#ifdef __cplusplus
75}
76#endif
77