我的应用程序涉及对用户设置的某些sqlite数据库进行备份。此备份基于某些条件。因此,为了做到这一点,我使用了一个工作对象(在QThread上运行)来检查条件是否匹配。如果条件匹配,我进行备份。我的问题是,我已经检查了任务管理器,并且我的应用程序始终至少使用25%(因为线程正在运行)。如果我禁用自动备份,它将恢复正常。我做错什么了吗?这是正常现象吗?请谁能指出我如何保持较低的CPU使用率?下面是我的自动备份线程代码。
void Automatic_Backup_Logic::Thread_Run()
{
QSettings settings(ORGANISATION, APPLICATION_NAME);
while(!m_Stop){
// First check the backup type
int backup_type = settings.value(BACKUP_TYPE).toInt();
QTime BackupTime = qvariant_cast<QTime>(settings.value(BACKUP_TIME));
// Check for backup time; if it's in range only then do backup
if(!Check_Backup_Time(BackupTime)){
continue;
}
switch (backup_type)
{
case BACKUP_TYPE_MANUAL:
// do nothing here
continue;
case BACKUP_TYPE_DAILY:
Backup_Daily();
break;
case BACKUP_TYPE_WEEKLY:
Backup_Weekly();
break;
case BACKUP_TYPE_MONTHLY:
Backup_Monthly();
break;
case BACKUP_TYPE_YEARLY:
Backup_Yearly();
break;
default:
break;
}
// Wait for the current backup minute to pass by to avoid multiple copies
QTime t1 = qvariant_cast<QTime> (settings.value(BACKUP_TIME));
while(t1.minute()==QTime::currentTime().minute()){
if(m_Stop)
return;
QCoreApplication::processEvents();
}
}
}
PS:我正在通过标准Qt过程运行此线程,该过程正在创建工作线程并使用moveToThread()函数
答案 0 :(得分:1)
解决此问题的一种干净方法是利用Qt的信号/插槽机制。
只需设置一个QTimer
剩余的备份时间,并将其timeout()
信号连接到备份插槽,例如:
class Automatic_Backup_Logic {
public:
Automatic_Backup_Logic() {
connect(&mBackupTimer, &QTimer::timeout, this, &Automatic_Backup_Logic::performBackup);
}
void scheduleBackup(QTime backupTime) {
int millisRemaining = getTimeRemaining(backupTime);
mBackupTimer.singleShot(millisRemaining);
}
private slots:
void performBackup() {
}
private:
QTimer mBackupTimer;
}
答案 1 :(得分:0)
正如评论中所建议的那样,我现在在线程中添加了延迟,现在一切正常。谢谢大家
修改后的代码
// Check for backup time; if it's in range only then do backup
while(!Check_Backup_Time(BackupTime) && !m_Stop){
QThread::sleep(1);
BackupTime = qvariant_cast<QTime>(settings.value(BACKUP_TIME));
}