1. 程式人生 > >Qt每天在固定時間執行一段程式

Qt每天在固定時間執行一段程式

    最近的專案過程中遇到了一些問題,需要在每天建立一個數據庫表格記錄相關資訊,查詢一些文章發現並不能實現對應功能,所以就依靠自己的想法在此獻醜了,希望大神能夠提出一些意見。

   核心的思想就是用Qtimer定時器,網上也有相關的例項,但運用中發現一些問題

QTimer *m_timer;
 
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(autoKeepSampleTimeOut()));

m_timer->start(1*1000*60); //every 1 minutes ,每分鐘呼叫一次

autoKeepSampleTimeOut()
 
 {
QDateTime datetime = QDateTime::currentDateTime();
if(datetime.toString("hh:mm") == "00:00")
{
    //do something

}

}

在此段程式中發現槽函式每分鐘觸發,但是觸發的時間是有誤差的。我希望在每天的0:00觸發函式,但實際上會根據這段函式的起調時間來判斷,並且槽函式被迴圈呼叫來對比時間。

    最後我用Qtime來獲取當先時間,QTimecurrent_time=QTime::currentTime(); 記錄當前時間。根據當前時間與下次觸發函式的時間差來既定Qtimer的槽函式。

     QTimecurrent_time=QTime
::currentTime();
QTimenext_time;
next_time.setHMS(0,0,0,0);//設定下次觸發的時間,時分秒毫秒
inttime_difference=current_time.secsTo(next_time)+24*60*60;
m_timer=newQTimer(this);
   m_timer->setSingleShot(1);//定時器單次觸發
m_timer->setTimerType(Qt::PreciseTimer);//設定定時器精度
connect(m_timer,SIGNAL(timeout()),this,SLOT(autoKeepSampleTimeOut()));
m_timer->start(time_difference*1000);//到達相應時間時,呼叫槽函式即可

如此,在每天0:00即可呼叫觸發槽函式,實現相應功能。誤差在秒級,對資料影響不大。

autoKeepSampleTimeOut()
{
m_timer=newQTimer(this);   
m_timer->setSingleShot(1);//定時器單次觸發
m_timer->setTimerType(Qt::PreciseTimer);//設定定時器精度
intmsec=QTime::currentTime().msec();//獲取當前毫秒數,進行定時器校準
connect(m_timer,SIGNAL(timeout()),this,SLOT(autoKeepSampleTimeOut()));
m_timer->start(24*60*60*1000-msec);//到達相應時間時,呼叫槽函式即可
}
如果想實現程式多天執行,每天都能夠呼叫槽函式,記得在槽函式中重新呼叫定時器,不然定時器所設定的時間有誤。