1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /*
18 * Asynchronous interval timer.
19 */
20
21 #include "IntervalTimer.h"
22
23 #include <android-base/logging.h>
24 #include <android-base/stringprintf.h>
25
26 using android::base::StringPrintf;
27
IntervalTimer()28 IntervalTimer::IntervalTimer() {
29 mTimerId = 0;
30 mCb = NULL;
31 }
32
set(int ms,TIMER_FUNC cb)33 bool IntervalTimer::set(int ms, TIMER_FUNC cb) {
34 if (mTimerId == 0) {
35 if (cb == NULL) return false;
36
37 if (!create(cb)) return false;
38 }
39 if (cb != mCb) {
40 kill();
41 if (!create(cb)) return false;
42 }
43
44 int stat = 0;
45 struct itimerspec ts;
46 ts.it_value.tv_sec = ms / 1000;
47 ts.it_value.tv_nsec = (ms % 1000) * 1000000;
48
49 ts.it_interval.tv_sec = 0;
50 ts.it_interval.tv_nsec = 0;
51
52 stat = timer_settime(mTimerId, 0, &ts, 0);
53 if (stat == -1)
54 LOG(ERROR) << StringPrintf("IntervalTimer::%s: fail set timer", __func__);
55 return stat == 0;
56 }
57
~IntervalTimer()58 IntervalTimer::~IntervalTimer() { kill(); }
59
kill()60 void IntervalTimer::kill() {
61 if (mTimerId == 0) return;
62
63 timer_delete(mTimerId);
64 mTimerId = 0;
65 mCb = NULL;
66 }
67
create(TIMER_FUNC cb)68 bool IntervalTimer::create(TIMER_FUNC cb) {
69 struct sigevent se;
70 int stat = 0;
71
72 /*
73 * Set the sigevent structure to cause the signal to be
74 * delivered by creating a new thread.
75 */
76 se.sigev_notify = SIGEV_THREAD;
77 se.sigev_value.sival_ptr = &mTimerId;
78 se.sigev_notify_function = cb;
79 se.sigev_notify_attributes = NULL;
80 se.sigev_signo = 0;
81 mCb = cb;
82 stat = timer_create(CLOCK_MONOTONIC, &se, &mTimerId);
83 if (stat == -1)
84 LOG(ERROR) << StringPrintf("IntervalTimer::%s: fail create timer",
85 __func__);
86 return stat == 0;
87 }
88