1 2 /** 3 * Tencent is pleased to support the open source community by making MSEC available. 4 * 5 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. 6 * 7 * Licensed under the GNU General Public License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. You may 9 * obtain a copy of the License at 10 * 11 * https://opensource.org/licenses/GPL-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software distributed under the 14 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 15 * either express or implied. See the License for the specific language governing permissions 16 * and limitations under the License. 17 */ 18 19 20 /** 21 * @file heap_timer.cpp 22 */ 23 24 #include "heap_timer.h" 25 #include "micro_thread.h" 26 27 using namespace NS_MICRO_THREAD; 28 29 CTimerMng::CTimerMng(uint32_t max_item) 30 { 31 #define TIMER_MIN 100000 32 33 if (max_item < TIMER_MIN) 34 { 35 max_item = TIMER_MIN; 36 } 37 38 _heap = new HeapList(max_item); 39 } 40 41 CTimerMng::~CTimerMng() 42 { 43 if (_heap) { 44 delete _heap; 45 _heap = NULL; 46 } 47 } 48 49 bool CTimerMng::start_timer(CTimerNotify* timerable, uint32_t interval) 50 { 51 if (!_heap || !timerable) { 52 return false; 53 } 54 55 utime64_t now_ms = MtFrame::Instance()->GetLastClock(); 56 timerable->set_expired_time(now_ms + interval); 57 int32_t ret = _heap->HeapPush(timerable); 58 if (ret < 0) { 59 MTLOG_ERROR("timer start failed(%p), ret(%d)", timerable, ret); 60 return false; 61 } 62 63 return true; 64 } 65 66 void CTimerMng::stop_timer(CTimerNotify* timerable) 67 { 68 if (!_heap || !timerable) { 69 return; 70 } 71 72 _heap->HeapDelete(timerable); 73 return; 74 } 75 76 void CTimerMng::check_expired() 77 { 78 if (!_heap) { 79 return; 80 } 81 82 utime64_t now = MtFrame::Instance()->GetLastClock(); 83 CTimerNotify* timer = dynamic_cast<CTimerNotify*>(_heap->HeapTop()); 84 while (timer && (timer->get_expired_time() <= now)) 85 { 86 _heap->HeapDelete(timer); 87 timer->timer_notify(); 88 timer = dynamic_cast<CTimerNotify*>(_heap->HeapTop()); 89 } 90 }; 91