【问题标题】:making a functionality of a rotator that creates a timestamp every minute of a day制作一个旋转器的功能,可以在一天中的每一分钟创建一个时间戳
【发布时间】:2012-04-21 18:01:11
【问题描述】:

我有一个日志项目,我需要知道如何构建一个功能,以便旋转器在程序运行时每分钟检查一次,并为每分钟创建时间戳,以便将全天的时间戳存储到日志文件中,请帮助。

谢谢

【问题讨论】:

  • 不知道从哪里开始
  • 我们不知道您应用的架构。你的要求不清楚。根据您的设计的其余部分,可以通过不同的方式使 dateTime 变量保持最新,以便可以为日志条目加上时间戳。也许您将不得不在记录器输出队列上等待超时,并在每次处理日志请求时重新计算超时。超时时,获取当前时间并重新加载用于时间戳的日期时间字符串。也许你可以在你的 GUI 表单上使用一个计时器,或者 System.Timer 也许。也许您应该编写一些代码并尝试让它自己工作?

标签: c++ logging rotator logrotate log-rotation


【解决方案1】:

满足您的需求的示例 Async Timer 类...

MyPeriodicTimer.hh

#include "MyTimeOutHandler.hh"
#include <pthread.h>
#include <iostream>

using namespace std;

void* func(void* ptr);


class MyPeriodicTimer
{
    public:
       MyPeriodicTimer(MyTimeOutHandler* handler,int ms){
            milliSecondsM = ms;
            handlerM = handler;
            createClock();
       }
       void act(){
            time_t rawtime;
            time ( &rawtime );
            handlerM->handleTimeOut(&rawtime);
            sleep(milliSecondsM);
       }
       pthread_t getThread(){
           return clockThreadM;
       }
private:

   void createClock(){
        int retVal = pthread_create( &clockThreadM,NULL,&func,(void*)this);
        pthread_join(clockThreadM,NULL);
    }
    int milliSecondsM;
    MyTimeOutHandler* handlerM;
    pthread_t clockThreadM;
};


void* func(void* obj){
    while(1){
      (reinterpret_cast<MyPeriodicTimer*>(obj))->act();
   }
}

定义处理超时的接口

MyTimeOutHandler.hh

#ifndef MY_TIMEOUT_HANDLER_HH
#define MY_TIMEOUT_HANDLER_HH

#include <time.h>

class MyTimeOutHandler{
  public:
    virtual void handleTimeOut(time_t*) = 0;
};


#endif

创建你的 LogHandler

LogHandler.cc

#include "MyTimeOutHandler.hh"
#include "MyPeriodicTimer.hh"
#include <iostream>
#include <time.h>

using namespace std;

class LogHandler : public MyTimeOutHandler{

  public:

    void start(int ms){
    MyPeriodicTimer timer(this,ms);
    }

    /* CallBack when timer is fired */
    void handleTimeOut(time_t* time){
        // Implement your Logging functionality Here
    cout<<"Time : "<<ctime(time)<<endl;
    }

};

int main(){
    LogHandler l;
    l.start(60);
     return 0;
}

输出:

>g++ -pthread LogHandler.cc

>./a.out
Time : Tue Apr 10 17:24:17 2012
Time : Tue Apr 10 17:25:17 2012
Time : Tue Apr 10 17:26:17 2012

【讨论】:

    【解决方案2】:

    我建议使用互斥锁进行检查:http://msdn.microsoft.com/en-us/library/ms686927%28VS.85%29.aspx 时间戳和日志文件与它无关。使用 MSDN - 你会在那里找到示例。

    【讨论】:

    • 这是对互斥锁的滥用。请参阅其他答案以获得更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 2021-07-14
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多