qt 线程QThread 采用QObject方式,使用QTimer注意事项

class RobotServer : public QObject
{
    Q_OBJECT
public:
    explicit RobotServer(QObject *parent = 0);
    ~RobotServer();
    static RobotServer* instance();
    void setConnectRobotForm(QObject *pWin);

signals:

public slots:
    void onChecking(); //分析聊天记录
private:
    static RobotServer *m_pInstance;
    QThread *m_thread;
    QTimer  *m_TaskTimer;
};

 

 

#include "robotserver.h"
#include <QDebug>

RobotServer* RobotServer::m_pInstance = NULL;
RobotServer::RobotServer(QObject *parent) :
    QObject(parent)
{
    //将本object移到线程中
    m_thread = new QThread();
    this->moveToThread(m_thread);
    m_thread->start();

    //创建定时器,并将timer移到线程中,同时启动定时器
    m_TaskTimer = new QTimer();
    m_TaskTimer->setInterval(1000);//1秒
    m_TaskTimer->moveToThread(m_thread);  //注意:将timer移到线程
    connect(m_TaskTimer, SIGNAL(timeout()), this, SLOT(onChecking()));
    connect(m_thread, SIGNAL(started()), m_TaskTimer,SLOT(start())); //让线程启用timer

    //m_TaskTimer->start();   //如果使用这句话,则容易报错,提示定时器不能在另一个线程中启用
}


RobotServer::~RobotServer()
{
    m_thread->quit();
    m_thread->wait();

    m_TaskTimer->stop();
    m_TaskTimer->deleteLater();

    m_thread->deleteLater();
    qDebug()<<"~RobotServer()";
}

RobotServer *RobotServer::instance()
{
    if(NULL == m_pInstance)
    {
        m_pInstance = new RobotServer();
    }
    return m_pInstance;
}

void RobotServer::onChecking()
{
    qDebug()<<tr("定时器任务......");
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值