Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #pragma once
00015
00019 #include "Clock.h"
00020
00021 namespace kNet
00022 {
00023
00024 class PolledTimer
00025 {
00026 public:
00028 PolledTimer():enabled(false)
00029 {
00030 startTime = Clock::Tick();
00031 }
00032
00033 explicit PolledTimer(float msecs)
00034 :enabled(false)
00035 {
00036 StartMSecs(msecs);
00037 }
00038
00040 void StartMSecs(float msecs)
00041 {
00042 StartTicks((tick_t)(Clock::TicksPerSec() * (msecs / 1000.f)));
00043 }
00044
00046 void StartTicks(tick_t ticks)
00047 {
00048 startTime = Clock::Tick();
00049 alarmTime = startTime + ticks;
00050 enabled = true;
00051 }
00052
00053 void Stop()
00054 {
00055 enabled = false;
00056 }
00057
00058 void Reset()
00059 {
00060 Stop();
00061 }
00062
00064 tick_t TicksElapsed() const
00065 {
00066 return Clock::Tick() - startTime;
00067 }
00068
00069 float MSecsElapsed() const
00070 {
00071 return Clock::TicksToMillisecondsF(TicksElapsed());
00072 }
00073
00076 void Start()
00077 {
00078 enabled = false;
00079 startTime = Clock::Tick();
00080 }
00081
00082 bool Enabled() const
00083 {
00084 return enabled;
00085 }
00086
00089 bool Test()
00090 {
00091 if (!enabled)
00092 return false;
00093 if (Clock::IsNewer(Clock::Tick(), alarmTime))
00094 {
00095 Reset();
00096 return true;
00097 }
00098 return false;
00099 }
00100
00101 bool TriggeredOrNotRunning()
00102 {
00103 return Test() || !Enabled();
00104 }
00105
00107 tick_t TicksLeft() const
00108 {
00109 if (!enabled)
00110 return (tick_t)(-1);
00111
00112 tick_t now = Clock::Tick();
00113 if (Clock::IsNewer(now, alarmTime))
00114 return 0;
00115 else
00116 return Clock::TicksInBetween(alarmTime, now);
00117 }
00118
00121 float MSecsLeft() const
00122 {
00123 if (!enabled)
00124 return -1.f;
00125
00126 tick_t now = Clock::Tick();
00127 if (Clock::IsNewer(now, alarmTime))
00128 return 0.f;
00129 else
00130 return Clock::TimespanToMillisecondsF(now, alarmTime);
00131 }
00132
00134 void WaitPrecise()
00135 {
00136 if (!enabled)
00137 return;
00138
00139 tick_t timeLeft = TicksLeft();
00140 while(timeLeft > 0)
00141 {
00142 if (timeLeft > Clock::TicksPerMillisecond())
00143 {
00144 float msecs = Clock::TicksToMillisecondsF(timeLeft);
00145 Clock::Sleep((int)msecs);
00146 }
00147 else
00148 {
00149 SpinWait();
00150 return;
00151 }
00152 timeLeft = TicksLeft();
00153 }
00154 }
00155
00157 void SpinWait()
00158 {
00159 while(enabled && TicksLeft() > 0)
00160 ;
00161 }
00162
00163 private:
00164 bool enabled;
00166 tick_t alarmTime;
00168 tick_t startTime;
00169 };
00170
00171 }
00172