qt 定时器任务在多线程中执行

 

#include <QTimer>
#include <QMutex> //多线程
#include <QThread>

 

 

    QThread* plantimer_thread = new QThread(this);
    QTimer* plantimer = new QTimer();
    plantimer->moveToThread(plantimer_thread);
    plantimer->setInterval(1500);
    //connect(plantimer_thread,&QThread::start, plantimer,&QTimer::start);//通过线程开启来触发定时器开启
    connect(plantimer_thread, SIGNAL(started()), plantimer, SLOT(start()));//通过线程开启来触发定时器开启
    connect(plantimer, &QTimer::timeout, this, &MainWindow::timerAutoSendSlots, Qt::DirectConnection);//信号发出后立即调用槽函数,槽函数在发出信号的线程中执行
    connect(plantimer_thread, &QThread::finished, this, &QObject::deleteLater);//线程结束,自动关闭线程
    plantimer_thread->start();



void MainWindow::timerAutoSendSlots()
{
    qDebug() << QStringLiteral("当前线程id:") << QThread::currentThread();
}
posted @ 2021-12-24 11:50  小城熊儿  阅读(1197)  评论(0编辑  收藏  举报