PDA

View Full Version : Execute a funcion at an exact time of day



KillGabio
24th May 2013, 21:44
I have this code:



QTimer *timer=new QTimer;
connect(timer, SIGNAL(timeout()),this,SLOT(delete_old_tuples()));
timer->start(3600000);




void MainWindow::delete_old_tuples(){
QDateTime now = QDateTime::currentDateTime();
QDateTime timeoftheaction (QDate (now.date()), QTime (15,0,0));
if (now >= timeoftheaction){
QMessageBox::critical(0, qApp->tr("Deleting tuples"),
qApp->tr("Click Cancel to exit."), QMessageBox::Cancel);
}
}


Is this code correct? I want to delete the tuples of my database everyday at 15:00....Is there a better way?

wysota
25th May 2013, 08:26
Is this code correct?
No


Is there a better way?

Yes. Setup a cron action (or whatever your platform's equivalent is).

KillGabio
28th May 2013, 03:38
Windows Task Scheduler should be. But SO annoying to learn.

ChrisW67
28th May 2013, 05:05
If you really don't want to use system features specifically built for the task then do it yourself.

Have your program wake up few seconds (or minute, whatever), look at the current time, and if it is within the timer period after the prescribed time have it do something. Then ensure that, no matter what, your program is always running (e.g. as a service or with a service acting as watchdog...).

Your current code only look once an hour to see if work needs to be done so it was never going to be "exactly" 15:00, and it would execute once an hour between 15:00 and midnight.

KillGabio
28th May 2013, 07:16
Yes I realized that. But after doing some research the delete of the rows can be done anytime between 15 and 17 so that gives me plenty of time to do it with the code posted. Lucky me! Thank you all :)

wysota
28th May 2013, 08:08
Yes I realized that. But after doing some research the delete of the rows can be done anytime between 15 and 17 so that gives me plenty of time to do it with the code posted. Lucky me! Thank you all :)

The problem is, with you current code the delete can happen many times during one day.