其他分享
首页 > 其他分享> > qt 定时器任务在多线程中执行

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

标签:定时器,qt,thread,start,plantimer,线程,connect,多线程,QThread
来源: https://www.cnblogs.com/RYSBlog/p/15726808.html