> 文档中心 > QT之QTimer详解以及结合多线程中开启定时器的示例

QT之QTimer详解以及结合多线程中开启定时器的示例

一 QTimer详解
QTimer类提供了重复和单次触发信号的定时器
a.void timeout ()定时器超时后,这个信号被发射。
b.void start()开启定时器,它的重载函数void start(int msec),启动或重新启动一个超时时间间隔为毫秒的定时器,如果定时器正在运行,它将被停止和重新启动。
c.void stop()停止定时器.
d.void setInterval(int msec)设置超时间隔(毫秒为单位)。

示例:

  QTimer *timer = new QTimer(this);     connect(timer, SIGNAL(timeout()), this, SLOT(update()));     timer->start(1000);//start之后,每隔一秒触发一次槽函数

二 在多线程中开启定时器的示例
示例:达到的效果,开启多个线程执行同一个耗时的操作,每个线程里,每隔多少时间去执行这个操作.

//调用示例QTimerThread *testObject = new QTimerThread(1);//创建几个线程    testObject->createItem();//调用开始创建线程的函数    testObject->startMultThread();//开启线程的函数

.h

#ifndef QTIMERTHREAD_H#define QTIMERTHREAD_H#include #include #include #include "tcpclient.h"class QTimerThread : public QObject{    Q_OBJECTpublic:    QTimerThread(int iCount);    ~QTimerThread();    void createItem();    void startMultThread();public slots:    void update();private:    int m_iThreadCount;//开启的线程个数    QList<QTimer*> m_qTimerList;    QList<QThread*> m_threadList;    };#endif // QTIMERTHREAD_H

.cpp

#include "qtimerthread.h"#include QTimerThread::QTimerThread(int iCount){    m_iThreadCount = iCount;}QTimerThread::~QTimerThread(){    for(int i = 0; i < m_iThreadCount; i++)    { m_threadList.value(i)->quit(); m_threadList.value(i)->wait(); m_qTimerList.value(i)->deleteLater(); m_threadList.value(i)->deleteLater();    }}void QTimerThread::createItem(){    for(int i = 0;i < m_iThreadCount;i++)    { QTimer *timer = new QTimer(); QThread  *thread = new QThread(); m_qTimerList.append(timer); m_threadList.append(thread);    }}void QTimerThread::startMultThread(){    for(int i = 0; i < m_qTimerList.size(); i++)    {    //划重点的部分 m_qTimerList.value(i)->start(5000); m_qTimerList.value(i)->moveToThread(m_threadList.value(i)); QObject::connect(m_qTimerList.value(i),SIGNAL(timeout()),this,SLOT(update()),Qt::QueuedConnection); m_threadList.value(i)->start();    }}void QTimerThread::update(){    //这里放需要耗时的操作      }

注:定时器的开启要放在最前面,不然会报错
QT之QTimer详解以及结合多线程中开启定时器的示例
翻译:QObject::startTimer: QTimer只能用于以QThread启动的线程

或许你会感兴趣的内容:
Qt封装一个类管理moveToThread( )正确的开启多线程、安全的退出线程的实例
QT 多线程 之MoveToThread使用详解
QT之处理密集响应时的保持(界面操作无反应)

ZDfans