drewpol
drewpol

Reputation: 697

Timer in thread's worker Qt

I'm trying to use timer in worker class. This is my Worker class:

Worker.h

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = nullptr);

signals:
    void finished(void);

public slots:
    void process(void);
    void test(void);

private:
    QMutex m_mutex;

};

Worker.cpp

void Worker::process(void)
{
    qDebug() << "worker process";       //This works
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(test()));

    forever
    {

    }
}

void Worker::test(void)
{
    qDebug() << "test123";   //This does not work
}

I start this worker class in new thread:

QThread *thread = new QThread;
    Worker *worker = new Worker;
    worker->moveToThread(thread);

    QObject::connect(thread, SIGNAL(started()), worker, SLOT(process()), Qt::QueuedConnection);
    QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
    QObject::connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));

    thread->start();

The problem is that timer from Worker::process does not work. Do I need to initialize this timer in new thread in special way?

Upvotes: 0

Views: 619

Answers (1)

Emir Cesovic
Emir Cesovic

Reputation: 39

You need to call void QTimer::start(int msec) or void QTimer::start() after you create the timer. You also don't need "forever" in your process() slot.

Try this instead:

void Worker::process(void)
{
    qDebug() << "worker process";       //This works
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(test()));
    timer->start(1000); // Fire timer timeout each 1000ms.
}

Upvotes: 1

Related Questions