FireBreath  1.4.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Pages
Timer.cpp
1 /**********************************************************\
2 Original Author: Mital Vora <mital.d.vora@gmail.com>
3 
4 Created: Mar 26, 2011
5 License: Dual license model; choose one of two:
6  New BSD License
7  http://www.opensource.org/licenses/bsd-license.php
8  - or -
9  GNU Lesser General Public License, version 2.1
10  http://www.gnu.org/licenses/lgpl-2.1.html
11 
12 \**********************************************************/
13 
14 #include "precompiled_headers.h" // On windows, everything above this line in PCH
15 #include <boost/asio.hpp>
16 #include "Timer.h"
17 #include "TimerService.h"
18 
19 using namespace FB;
20 
21 namespace FB {
22  class TimerPimpl {
23  public:
24  TimerPimpl() : timerService(TimerService::instance()), timer(*timerService->getIOService()) {
25  }
26 
27  TimerServicePtr timerService;
28  boost::asio::deadline_timer timer;
29  };
30 };
31 
32 TimerPtr Timer::getTimer(long _duration, bool _recursive, TimerCallbackFunc _callback)
33 {
34  return boost::shared_ptr<FB::Timer>(new Timer(_duration, _recursive, _callback));
35 }
36 
37 Timer::Timer(long _duration, bool _recursive, TimerCallbackFunc _callback)
38  : duration(_duration),
39  recursive(_recursive),
40  cb(_callback), pimpl(new TimerPimpl)
41 {
42 }
43 
44 Timer::~Timer()
45 {
46  this->stop();
47 }
48 
49 
50 void Timer::callback(const boost::system::error_code& error)
51 {
52  if (error)
53  {
54  if (error == boost::asio::error::operation_aborted)
55  {
56  return;
57  }
58  // TODO: prompt timer Error.
59  return;
60  }
61 
62  if (this->recursive)
63  {
64  this->start();
65  }
66  if (cb) cb();
67 }
68 
69 void Timer::start()
70 {
71  pimpl->timer.expires_from_now(boost::posix_time::milliseconds(duration));
72  pimpl->timer.async_wait(boost::bind(&Timer::callback, this, boost::asio::placeholders::error));
73 }
74 bool Timer::stop()
75 {
76  pimpl->timer.cancel();
77  return false;
78 }
79 
TimerService Utility.
Definition: TimerService.h:38
Timer Utility.
Definition: Timer.h:39