Unable to match current Date and time in Qt

867 views Asked by At

I am writing a simple task planner and reminder using Qt which will play a sound file when the date and time of any given task matches with the the current date and time.

To implement this, I am running a QThread which checks the task in the list to see if any match the current time and if so, plays the sound file.

This id my original class:

class Task
{
  public:
      QString ta, desc;
      QTime ti;
      QDate da;
      int pri, diff;
      bool ala;
};  

This is my Thread Class:

class AlarmCheck : public QThread
{
  public:
      void setTask(QList<Task>);
      void run();
      bool isRunning;
      QString music;
      QTime alarmOffset;

  private:
      QList<Task> list;
};

My Implementation:

void AlarmCheck::setTask(QList<Task> l)
{
    list = l;
}

void AlarmCheck::run()
{
    while(isRunning)
    {
        foreach(Task t, list)
        {
            if((t.da == QDate::currentDate()) && (t.ti == QTime::currentTime()) && t.ala)
            {
                Phonon::MediaObject *gaana =
                        Phonon::createPlayer(Phonon::MusicCategory,
                                              Phonon::MediaSource(music));
                gaana->play();
                QMessageBox::information(NULL,
                                         "Alarm!!!",
                                         "The time has come for\n"
                                         + t.ta +
                                         "\n Time to do it!");
                gaana->stop();
            }
            qDebug("Curr = " + QTime::currentTime().toString().toAscii() + " Date = " + QDate::currentDate().toString().toAscii());
            qDebug("Task = " + t.ti.toString().toAscii() + " Date = " + t.da.toString().toAscii());                
        }
        sleep(1);
    }
}  

The thing is that the thread is running perfectly, but the if() condition inside the foreach() loop is never satisfied for some reason. I even checked the individual date/time/alarm setting (t.ala) using qDebugs (as you can see); they are all fine.

1

There are 1 answers

3
Dave Mateer On BEST ANSWER

Your if statement requires that the date and time match exactly, down to the millisecond. It is unlikely that your loop will evaluate at this exact moment. If you want to maintain similar logic (processing tasks in a loop), you might try sorting them by "next task first" (or perhaps using a queue), then testing in your if statement if the current QDateTime is equal-to-or-greater than the task date/time of the first task.