RDK Documentation (Open Sourced RDK Components)
timer.cpp
1 /*
2  * If not stated otherwise in this file or this component's Licenses.txt file the
3  * following copyright and licenses apply:
4  *
5  * Copyright 2018 RDK Management
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18 */
19 #include "timer.h"
20 #include <glib.h>
21 
23 public:
24  explicit TimerBaseImpl(TimerBase* pub)
25  : m_pub(pub)
26  , m_tag(0) {
27  }
28 
29  virtual ~TimerBaseImpl() {
30  if (m_tag)
31  g_source_remove(m_tag);
32  m_tag = 0;
33  }
34 
35  void start(double nextFireInterval) {
36  guint delay = (guint)(nextFireInterval * 1000);
37  if (m_tag)
38  g_source_remove(m_tag);
39  m_tag = g_timeout_add(delay, [](gpointer data) -> gboolean {
40  TimerBaseImpl &self = *static_cast<TimerBaseImpl*>(data);
41  self.m_tag = 0;
42  self.m_pub->fired();
43  return G_SOURCE_REMOVE;
44  }, this);
45  }
46 
47  bool isActive() const {
48  return m_tag != 0;
49  }
50 
51 private:
52  TimerBase* m_pub;
53  guint m_tag;
54 };
55 
56 TimerBase::TimerBase() : m_impl(nullptr) {
57 }
58 
59 TimerBase::~TimerBase() {
60  stop();
61 }
62 
63 void TimerBase::startOneShot(double interval) {
64  if (!m_impl)
65  m_impl = new TimerBaseImpl(this);
66  m_impl->start(interval);
67 }
68 
69 void TimerBase::stop() {
70  if (m_impl) {
71  delete m_impl;
72  m_impl = nullptr;
73  }
74 }
75 
76 bool TimerBase::isActive() const {
77  return m_impl && m_impl->isActive();
78 }
TimerBase
Definition: timer.h:24
TimerBaseImpl
Definition: timer.cpp:22