首页 > 代码库 > 定时器-每秒记录日志
定时器-每秒记录日志
1 #include<iostream> 2 #include<windows.h> 3 #include <MMSystem.h> 4 #pragma comment(lib, "winmm.lib") 5 #include<time.h> 6 #include<stdint.h> 7 using namespace std; 8 9 #define MAX_LOG_FILE_SIZE 0x4000000 //64MB10 11 class CTimer{12 public:13 CTimer()14 {15 m_tickCount = 0;16 }17 ~CTimer()18 {19 if(m_timerID)20 {21 timeKillEvent(m_timerID);22 }23 }24 static void CALLBACK TimerCallBack(UINT uTimeID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);25 void OnTimer();26 void Log(const char* fmt,...);27 28 protected:29 void Call()30 {31 Log("tick...%d",m_tickCount);32 ++m_tickCount;33 }34 void print_format_time(FILE* fileName);35 36 private:37 MMRESULT m_timerID;38 int m_tickCount;39 };40 41 void CALLBACK CTimer::TimerCallBack(UINT uTimeID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)42 {43 CTimer *_ctimer = (CTimer*)dwUser;44 _ctimer->Call();45 }46 47 void CTimer::OnTimer()48 {49 timeSetEvent(1000,1,(LPTIMECALLBACK)TimerCallBack,(DWORD)this,TIME_PERIODIC);50 }51 52 void CTimer::print_format_time(FILE* fileName)53 {54 SYSTEMTIME _sysTime;55 GetLocalTime(&_sysTime);56 57 fprintf(fileName,"%04d-%02d-%02d %02d:%02d:%02d.%06d ",_sysTime.wYear,58 _sysTime.wMonth,_sysTime.wDay,_sysTime.wHour,_sysTime.wMinute,_sysTime.wSecond,_sysTime.wMilliseconds);59 }60 61 void CTimer::Log(const char* fmt,...)62 {63 static int file_no(0);64 static FILE* log_fp = NULL;65 if(log_fp == NULL)66 {67 char log_name[64];68 uint32_t pid;69 pid = (uint32_t)GetCurrentProcessId();70 sprintf_s(log_name,64,"log_%d_%d.txt",pid,file_no);71 fopen_s(&log_fp,log_name,"w");72 if(!log_fp)73 return;74 }75 print_format_time(log_fp);76 77 va_list ap;78 va_start(ap,fmt);79 vfprintf_s(log_fp,fmt,ap);80 va_end(ap);81 fflush(log_fp);82 fprintf(log_fp,"\n");83 if(ftell(log_fp) > MAX_LOG_FILE_SIZE)84 {85 fclose(log_fp);86 log_fp = NULL;87 ++file_no;88 }89 90 }91 92 int main(int argc, char* argv[])93 {94 CTimer _timer;95 _timer.OnTimer();96 system("pause");97 return 0;98 }
定时器-每秒记录日志
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。