Home | History | Annotate | Download | only in jni
      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/stringprintf.h>
     24 #include <base/logging.h>
     25 
     26 using android::base::StringPrintf;
     27 
     28 IntervalTimer::IntervalTimer() {
     29   mTimerId = 0;
     30   mCb = NULL;
     31 }
     32 
     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) LOG(ERROR) << StringPrintf("fail set timer");
     54   return stat == 0;
     55 }
     56 
     57 IntervalTimer::~IntervalTimer() { kill(); }
     58 
     59 void IntervalTimer::kill() {
     60   if (mTimerId == 0) return;
     61 
     62   timer_delete(mTimerId);
     63   mTimerId = 0;
     64   mCb = NULL;
     65 }
     66 
     67 bool IntervalTimer::create(TIMER_FUNC cb) {
     68   struct sigevent se;
     69   int stat = 0;
     70 
     71   /*
     72    * Set the sigevent structure to cause the signal to be
     73    * delivered by creating a new thread.
     74    */
     75   se.sigev_notify = SIGEV_THREAD;
     76   se.sigev_value.sival_ptr = &mTimerId;
     77   se.sigev_notify_function = cb;
     78   se.sigev_notify_attributes = NULL;
     79   mCb = cb;
     80   stat = timer_create(CLOCK_MONOTONIC, &se, &mTimerId);
     81   if (stat == -1) LOG(ERROR) << StringPrintf("fail create timer");
     82   return stat == 0;
     83 }
     84