在早期开发的软件中,尤其是初学者入门者写的软件,软件运行久了,难免遇到意外崩溃的时候,可是大部分的运行设备可能在现场客户那,需要记住每一次从软件启动后到软件意外关闭前的运行时间,需要记录的信息包括:编号+开始时间+结束时间+已运行时间,每次完整的运行过程只产生一条记录,每次运行时间改变以后更新当前这条记录即可。这样就可以确切的了解到软件在现场的真实运行情况是否糟糕,如果没有这个记录(当然可以选择记录存储到数据库),程序又重启恢复了,也不知道到底每次运行了多久,从几点到几点。
为了写的简单点,不干扰原有的数据库文件,我一般选择输出到文本文件。
完整代码下载: https://download.csdn.net/download/feiyangqingyun/11010447
完整代码:
#ifndef SAVERUNTIME_H
#define SAVERUNTIME_H #include <QObject>
#include <QDateTime>
class QTimer; #ifdef quc
#if (QT_VERSION < QT_VERSION_CHECK(5,7,0))
#include <QtDesigner/QDesignerExportWidget>
#else
#include <QtUiPlugin/QDesignerExportWidget>
#endif class QDESIGNER_WIDGET_EXPORT SaveRunTime : public QObject
#else
class SaveRunTime : public QObject
#endif {
Q_OBJECT
public:
static SaveRunTime *Instance();
explicit SaveRunTime(QObject *parent = ); private:
static QScopedPointer<SaveRunTime> self;
QString path; //日志文件路径
QString name; //日志文件名称 int lastID;
int saveInterval;
QDateTime startTime;
QString logFile;
QTimer *timerSave; private:
void getDiffValue(const QDateTime &startTime, const QDateTime &endTime, int &day, int &hour, int &minute); signals: public slots:
void start(); //启动服务
void stop(); //停止服务
void initLog(); //初始化日志文件
void appendLog(); //追加一条记录到日志文件
void saveLog(); //保存运行时间到日志文件 void setPath(const QString &path);
void setName(const QString &name);
void setSaveInterval(int saveInterval);
}; #endif // SAVERUNTIME_H
#include "saveruntime.h"
#include "qmutex.h"
#include "qapplication.h"
#include "qtimer.h"
#include "qfile.h"
#include "qtextstream.h"
#include "qstringlist.h"
#include "qdebug.h" #ifdef Q_OS_WIN
#define NEWLINE "\r\n"
#else
#define NEWLINE "\n"
#endif QScopedPointer<SaveRunTime> SaveRunTime::self;
SaveRunTime *SaveRunTime::Instance()
{
if (self.isNull()) {
QMutex mutex;
QMutexLocker locker(&mutex);
if (self.isNull()) {
self.reset(new SaveRunTime);
}
} return self.data();
} SaveRunTime::SaveRunTime(QObject *parent) : QObject(parent)
{
path = qApp->applicationDirPath();
QString str = qApp->applicationFilePath();
QStringList list = str.split("/");
name = list.at(list.count() - ).split(".").at(); saveInterval = * * ;
startTime = QDateTime::currentDateTime(); timerSave = new QTimer(this);
timerSave->setInterval(saveInterval);
connect(timerSave, SIGNAL(timeout()), this, SLOT(saveLog()));
} void SaveRunTime::start()
{
timerSave->start(); initLog();
appendLog();
saveLog();
} void SaveRunTime::stop()
{
timerSave->stop();
} void SaveRunTime::getDiffValue(const QDateTime &startTime, const QDateTime &endTime, int &day, int &hour, int &minute)
{
qint64 sec = startTime.secsTo(endTime);
day = hour = minute = ;
int seconds = ; while (sec > ) {
seconds++;
if (seconds == ) {
minute++;
seconds = ;
} if (minute == ) {
hour++;
minute = ;
} if (hour == ) {
day++;
hour = ;
} sec--;
}
} void SaveRunTime::initLog()
{
//判断当前年份的记事本文件是否存在,不存在则新建并且写入标题
//存在则自动读取最后一行的id号 记事本文件格式内容
//编号 开始时间 结束时间 已运行时间
//1 2016-01-01 12:33:33 2016-02-05 12:12:12 day: 0 hour: 0 minute: 0 logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year());
QFile file(logFile); if (file.size() == ) {
if (file.open(QFile::WriteOnly | QFile::Text)) {
QString strID = QString("%1\t").arg("编号");
QString strStartTime = QString("%1\t\t").arg("开始时间");
QString strEndTime = QString("%1\t\t").arg("结束时间");
QString strRunTime = QString("%1").arg("已运行时间");
QString line = strID + strStartTime + strEndTime + strRunTime; QTextStream stream(&file);
stream << line << NEWLINE;
file.close(); lastID = ;
}
} else {
if (file.open(QFile::ReadOnly)) {
QString lastLine; while (!file.atEnd()) {
lastLine = file.readLine();
} file.close(); QStringList list = lastLine.split("\t");
lastID = list.at().toInt();
}
} lastID++;
} void SaveRunTime::appendLog()
{
logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year());
QFile file(logFile); //写入当前首次运行时间
if (file.open(QFile::WriteOnly | QFile::Append | QFile::Text)) {
QString strID = QString("%1\t").arg(lastID);
QString strStartTime = QString("%1\t").arg(startTime.toString("yyyy-MM-dd HH:mm:ss"));
QString strEndTime = QString("%1\t").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); int day, hour, minute;
getDiffValue(startTime, QDateTime::currentDateTime(), day, hour, minute);
QString strRunTime = QString("%1 天 %2 时 %3 分").arg(day).arg(hour).arg(minute);
QString line = strID + strStartTime + strEndTime + strRunTime; QTextStream stream(&file);
stream << line << NEWLINE;
file.close();
}
} void SaveRunTime::saveLog()
{
//每次保存都是将之前的所有文本读取出来,然后替换最后一行即可
logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year());
QFile file(logFile); //如果日志文件不存在,则初始化一个日志文件
if (file.size() == ) {
initLog();
appendLog();
return;
} if (file.open(QFile::ReadWrite)) {
//一行行读取到链表
QStringList content;
while (!file.atEnd()) {
content.append(file.readLine());
} //重新清空文件
file.resize(); //如果行数小于2则返回
if (content.count() < ) {
file.close();
return;
} QString lastLine = content.last();
QStringList list = lastLine.split("\t"); //计算已运行时间
int day, hour, minute;
getDiffValue(startTime, QDateTime::currentDateTime(), day, hour, minute);
QString strRunTime = QString("%1 天 %2 时 %3 分").arg(day).arg(hour).arg(minute); //重新拼接最后一行
list[] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
list[] = strRunTime;
lastLine = list.join("\t"); //重新替换最后一行并写入新的数据
content[content.count() - ] = lastLine; QTextStream stream(&file);
stream << content.join("") << NEWLINE;
file.close();
}
} void SaveRunTime::setPath(const QString &path)
{
if (this->path != path) {
this->path = path;
}
} void SaveRunTime::setName(const QString &name)
{
if (this->name != name) {
this->name = name;
}
} void SaveRunTime::setSaveInterval(int saveInterval)
{
if (this->saveInterval != saveInterval) {
this->saveInterval = saveInterval;
timerSave->setInterval(saveInterval);
}
}