[SOLVED]Execute function at a specific time



  • How do I call a function at a specific time?
    For example I want to execute function launch() on 18/02/2012 15:35:01 .


  • Moderators

    If you want to do it through Qt you may want to have a look to "QTimer":http://developer.qt.nokia.com/doc/qt-4.8/qtimer.html



  • Hi,

    You could inherit from QTime and poll the current time in the object. When it reaches the time you want, emit a signal.

    Hope that helps ;O)



  • I was thinking of using QTimer this way:
    Create a QTimer object that emits a signal every second.
    When the signal is emited I remove a seconds from some sort of Countdown timer that when reaches 0 launch the function that I want.I think that this way is consuming too much resources that's why I asked help :),maybe someone knows a better way.My knowledge in QT is not too good but I learn fast.
    Sorry for my bad english.



  • There's also QDateTime which is probably better than QTime, as it provides AM/PM too.
    So you could do something like this: -

    @
    class QActOnDateTime : public QDateTime
    {
    Q_OBJECT
    private:

         int timerID;
         QDateTime checkTime;
    
         void Init()
         {
             timerId = startTimer(1000);  // start a timer at 1 second intervals
         }
    
         void timerEvent(QTimerEvent* evt)
         {
             if(evt->timerId() == timerID)
             {
                 if(currentDateTime() >= checkTime)
                 {
                       // call function due to elapsed time
                       DoSomething();
                 }
             }
         }
    

    };
    @


  • Moderators

    The simplistic "Count down some timer every second" is going to fail when you loose/gain an hour due to daylight saving time.

    Why not get the current QDateTime every minute and only use a QTimer for the last couple of seconds (if you need that kind of resolution)? The fewer wakeups your application triggers the less power your computer is going to consume.



  • How about this:
    @QDateTime now = QDateTime::currentDateTime();
    QDateTime timeoftheaction;
    QTimer *timer=new QTimer;
    connect(timer, SIGNAL(timeout()),object,SLOT(action);
    timer->start(now.secsTo(timeoftheaction)*1000);@
    Isn't this aproach better?


  • Moderators

    It is... once you managed to abolish daylight saving time and had your user sign a contract stating that he will never set the clock.



  • If you assume, the user changes the clock, you can forget that stuff without "polling via timer".
    I would convert both times to UTC, to be sure DST is in calculation.



  • I'll read the current time from a server and then I'll convert it to UTC.Thank you for your help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.