RDK Documentation (Open Sourced RDK Components)
QtTimer.h
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 2016 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 
20 
21 /**
22 * @defgroup trm
23 * @{
24 * @defgroup qtapp
25 * @{
26 **/
27 
28 
29 #ifndef TRM_QT_TIMER_H_
30 #define TRM_QT_TIMER_H_
31 #include <iostream>
32 
33 #include <QObject>
34 #include <QTimer>
35 #include <QMutex>
36 #include <QDate>
37 #include <QTime>
38 #include <limits>
39 
40 #include "trm/TRM.h"
41 #include "trm/Timer.h"
42 
43 namespace TRM {
44 
45 extern std::ostream & Log(void) ;
46 
47 //@TODO: Synchronization.
48 
49 #define _TRIM_QT_TIMER_BYPASS_PRECISION_CHECK_ 0
50 
51 class QtTimer : public QObject
52 {
53  Q_OBJECT
54 public:
55  QtTimer(void)
56  : QObject(0)
57  {
58  timer.setSingleShot(true);
59  task = 0;
60  future = 0;
61  QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(onExpiration()));
62  };
63  ~QtTimer(void) {};
64 
65  void schedule(TimerTask &task, int64_t expireAt, int64_t milliSecs)
66  {
67 
68  int32_t max32 = std::numeric_limits<int32_t>::max();
69  mutex.lock();
70  future = expireAt;
71  this->task = &task;
72  milliSecs = (milliSecs <= ((int64_t)max32)) ? milliSecs : max32;
73  timer.start(milliSecs);
74  mutex.unlock();
75  }
76  void cancel(void)
77  {
78  mutex.lock();
79  timer.stop();
80  task = 0;
81  future = 0;
82  mutex.unlock();
83  }
84 
85 private slots:
86  void onExpiration(void)
87  {
88  qint64 now = QDateTime::currentMSecsSinceEpoch();
89  if (_TRIM_QT_TIMER_BYPASS_PRECISION_CHECK_ || now >= future) {
90  if (task) {
91  TimerTask *task2 = task->clone();
92  task2->run();
93  delete task2;
94  }
95  future = 0;
96  }
97  else {
98  int64_t milliSecs = future - now + 1;
99  milliSecs = ((milliSecs > 0) ? milliSecs : 0);
100  Log() << "WARN::Timer " << (void *)this << " Expired Earlyy, Reschedule " << (milliSecs) << " with future " << future << std::endl;
101  /* schedule again */
102  mutex.lock();
103  timer.setSingleShot(true);
104  timer.start(milliSecs);
105  mutex.unlock();
106  }
107  }
108 
109 public:
110  QMutex mutex;
111  TimerTask *task;
112  QTimer timer;
113  qint64 future;
114 };
115 
116 }
117 #endif
118 
119 
120 /** @} */
121 /** @} */
TRM::QtTimer
Definition: QtTimer.h:51
TRM::TimerTask
Definition: Timer.h:37