Source code analysis in qtimer (using Windows as an example)
In the article, we see the usage of timer in Windows using QT:
- When the interval is zero, QT does not use the system timer.
- Non-zero Interval
- The multimedia timer is used when the interval is less than 20 ms and the system supports multimedia timers.
- Otherwise, use a common timer.
Qt's policy should be able to meet our needs well, but a user on qtcn was expecting to call the system's multimedia timer directly. In this case, write your own Timer class.
Code
- The code is relatively simple. The header file mmtimer. H is as follows:
#ifndef MMTIMER_H#define MMTIMER_H#include <qt_windows.h>#include <QtCore/QObject>class MMTimer : public QObject{ Q_OBJECTpublic: explicit MMTimer(int interval, QObject *parent = 0); ~MMTimer();signals: void timeout();public slots: void start(); void stop();friend void WINAPI CALLBACK mmtimer_proc(uint, uint, DWORD_PTR, DWORD_PTR, DWORD_PTR);private: int m_interval; int m_id;};#endif // MMTIMER_H
- The source code file mmtimer. cpp is as follows:
#include "mmtimer.h"#include <MMSystem.h>#ifdef __MINGW32__ //w32api bug#define TIME_KILL_SYNCHRONOUS 0x0100#endifvoid WINAPI CALLBACK mmtimer_proc(uint timerId, uint, DWORD_PTR user, DWORD_PTR, DWORD_PTR){ MMTimer *t = reinterpret_cast<MMTimer*>(user); emit t->timeout();}MMTimer::MMTimer(int interval, QObject *parent) : QObject(parent),m_interval(interval),m_id(0){}MMTimer::~MMTimer(){ stop();}void MMTimer::start(){ m_id = timeSetEvent(m_interval, 1, mmtimer_proc, (DWORD_PTR)this, TIME_CALLBACK_FUNCTION | TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);}void MMTimer::stop(){ if (m_id){ timeKillEvent(m_id); m_id = 0; }}
Description
The above Code does not need to be explained:
- For more information about timesetevent and timekillevent, see msdn.
- In addition, the WIN32API package of mingw does not define time_kill_synchronous, and some modifications are made in the Code.
Make sure that the required libraries are correctly linked.
LIBS += -lwinmm
Note: This is what msdn says in its introduction to timesetevent (this is not a comment)
Note This function is obsolete. New applications should use CreateTimerQueueTimer to create a timer-queue timer.