TimerHandle.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #ifndef NU_THREADPOOL_TIMERHANDLE_H
  2. #define NU_THREADPOOL_TIMERHANDLE_H
  3. #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x400)
  4. #error Must define _WIN32_WINNT >= 0x400 to use TimerHandle
  5. #endif
  6. #include <windows.h>
  7. #include <bfc/platform/types.h>
  8. /*
  9. TimerHandle() constructor will make a new timer handle
  10. TimerHandle(existing_handle) will "take over" an existing handle
  11. ~TimerHandle() DOES NOT CloseHandle as this object is meant as a helper
  12. call Close() to kill the timer handle
  13. The timer will be "one shot" auto-reset.
  14. Because it is meant to be compatible with the threadpool, manual-reset timers and periodic timers
  15. are not recommended!! You will have re-entrancy problems
  16. If you want "periodic" behavior, call Wait() at the end of your ThreadPoolFunc
  17. */
  18. class TimerHandle
  19. {
  20. public:
  21. TimerHandle() { timerHandle = CreateWaitableTimer( 0, FALSE, 0 ); }
  22. TimerHandle( HANDLE p_handle ) { timerHandle = p_handle; }
  23. void Close() { CloseHandle( timerHandle ); }
  24. void Wait( uint64_t p_milliseconds )
  25. {
  26. /* MSDN notes about SetWaitableTimer: 100 nanosecond resolution, Negative values indicate relative time*/
  27. LARGE_INTEGER timeout = { 0 };
  28. timeout.QuadPart = -( (int64_t)p_milliseconds * 1000LL /*to microseconds*/ * 10LL /* to 100 nanoseconds */ );
  29. SetWaitableTimer( timerHandle, &timeout, 0, 0, 0, FALSE );
  30. }
  31. void Poll( uint64_t p_milliseconds ) // only use on a reserved thread!!!
  32. {
  33. /* MSDN notes about SetWaitableTimer: 100 nanosecond resolution, Negative values indicate relative time*/
  34. LARGE_INTEGER timeout = { 0 };
  35. timeout.QuadPart = -( (int64_t)p_milliseconds * 1000LL /*to microseconds*/ * 10LL /* to 100 nanoseconds */ );
  36. SetWaitableTimer( timerHandle, &timeout, (LONG)p_milliseconds, 0, 0, FALSE );
  37. }
  38. /* TODO: WaitUntil method for absolute times */
  39. void Cancel() { CancelWaitableTimer( timerHandle ); }
  40. operator HANDLE() { return timerHandle; }
  41. private:
  42. HANDLE timerHandle;
  43. };
  44. #endif // !NU_THREADPOOL_TIMERHANDLE_H