hassan panahi hassan panahi - 1 year ago 77
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
statements in my code and check time. i mean:

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

how is it possible?

Answer Source

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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download