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("定时器任务......");
}