hassan panahi hassan panahi - 1 month ago 15
C++ Question

Sending signal in Special Time like hh:mm with Qt

I am trying to send a signal in special time like every day in 22:23 o'clock with Qt Library.

I want to use something like this function:

QTimer::singleShot("22:23", this, SLOT(updateCaption()));


I don't want to use
if
statements in my code and check time. i mean:

if( time == "22:23" )
emit mysignal();


how is it possible?

Answer

Here's how I'd do this.

First, get the datetime of the next time you want to emit the signal:

auto then = QDateTime::currentDateTime();
auto setTime = QTime::fromString("22:23", "hh:mm");
if(then.time() > setTime){
    then = then.addDays(1);
}
then.setTime(setTime);

calculate the time difference from now

auto diff = QDateTime::currentDateTime().msecsTo(then);

and start a singleshot timer at that time, to start the regular daily timer:

QTimer::singleShot(diff, [this]{
    auto t = new QTimer(QCoreApplication::instance());
    connect(t, &QTimer::timeout, [this]{
        emit mysignal();
    });
    t->start(24 * 3600 * 1000);
});

Note that this will be an hour off when the daylight saving time changes.

Comments