wsTimerThread.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #include "wsTimerThread.h"
  2. #include <iostream>
  3. #include "wsClientMgr.h"
  4. #include "constdef.h"
  5. namespace YA
  6. {
  7. wsTimerThread::wsTimerThread()
  8. {
  9. __Reset();
  10. __LastSendTime = { 0 };
  11. __LastSendTime.tm_year = 1970 - 1900;
  12. __LastSendTime.tm_mon = 1;
  13. __LastSendTime.tm_mday = 1;
  14. }
  15. wsTimerThread::~wsTimerThread()
  16. {
  17. Stop();
  18. }
  19. void wsTimerThread::Start()
  20. {
  21. __Running = true;
  22. __Thread.reset( new boost::thread( boost::bind( &wsTimerThread::_ThreadFunc, this, this ) ) );
  23. __Thread->detach();
  24. }
  25. void wsTimerThread::Stop()
  26. {
  27. std::cout << "::Stop() begin" << std::endl;
  28. __Enable = false;
  29. if ( __Running )
  30. {
  31. boost::unique_lock<boost::mutex> lock( __ExitMutex );
  32. __ExitCond.wait( lock );
  33. }
  34. __Reset();
  35. std::cout << "::Stop() end" << std::endl;
  36. }
  37. void wsTimerThread::__Reset()
  38. {
  39. __Enable = true;
  40. __Running = false;
  41. }
  42. void wsTimerThread::__ChkConfig()
  43. {
  44. if ( __Config.SendInterval < MIN_SEND_INTERVAL )
  45. {
  46. __Config.SendInterval = MIN_SEND_INTERVAL;
  47. }
  48. }
  49. void wsTimerThread::__SendCardPos()
  50. {
  51. std::map<int, _CARD_POS_> CardPosList;
  52. __CardPosList.copy( CardPosList );
  53. std::string jsCardPos = __jsBuilder.BuildCardPos( CardPosList );
  54. swsClientMgr.send( JSON_CMD_VALUE_PUSH, jsCardPos );
  55. }
  56. void wsTimerThread::_ThreadFunc( wsTimerThread * pOwner )
  57. {
  58. while ( pOwner->__Enable )
  59. {
  60. std::tm *Now;
  61. std::time_t t;
  62. t = time( 0 );
  63. Now = localtime( &t );
  64. int seconds = (int)std::difftime( mktime( Now ), mktime( &__LastSendTime ) );
  65. if ( seconds >= pOwner->__Config.SendInterval )
  66. {
  67. pOwner->__SendCardPos();
  68. __LastSendTime = *Now;
  69. }
  70. boost::this_thread::sleep( boost::posix_time::millisec( 1 ) );
  71. }
  72. pOwner->__ExitCond.notify_one();
  73. }
  74. void wsTimerThread::Init( const _THREAD_CONFIG_ & Config )
  75. {
  76. __Config = Config;
  77. __ChkConfig();
  78. }
  79. void wsTimerThread::upt_card_pos( const _CARD_POS_ & pos )
  80. {
  81. //如果已存在就更新,否则插入
  82. if ( __CardPosList.seek( pos.ID ) )
  83. {
  84. __CardPosList.update( pos.ID, pos );
  85. }
  86. else
  87. {
  88. __CardPosList.insert( pos.ID, pos );
  89. }
  90. }
  91. void wsTimerThread::del_card_pos( const _CARD_POS_ & pos )
  92. {
  93. __CardPosList.erase( pos.ID );
  94. }
  95. }