QChronoTimer Class

The QChronoTimer class provides repetitive and single-shot timers. More...

Header: #include <QChronoTimer>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Since: Qt 6.8
Inherits: QObject

Properties

Public Functions

QChronoTimer(QObject *parent = nullptr)
QChronoTimer(std::chrono::nanoseconds nsec, QObject *parent = nullptr)
virtual ~QChronoTimer() override
QBindable<bool> bindableActive()
QBindable<std::chrono::nanoseconds> bindableInterval()
QBindable<bool> bindableSingleShot()
QBindable<Qt::TimerType> bindableTimerType()
QMetaObject::Connection callOnTimeout(const QObject *context, Functor &&slot, Qt::ConnectionType connectionType = Qt::AutoConnection)
Qt::TimerId id() const
std::chrono::nanoseconds interval() const
bool isActive() const
bool isSingleShot() const
std::chrono::nanoseconds remainingTime() const
void setInterval(std::chrono::nanoseconds nsec)
void setSingleShot(bool singleShot)
void setTimerType(Qt::TimerType atype)
Qt::TimerType timerType() const

Public Slots

void start()
void stop()

Signals

void timeout()

Static Public Members

void singleShot(std::chrono::nanoseconds interval, Qt::TimerType timerType, const QObject *receiver, const char *member)

Reimplemented Protected Functions

virtual void timerEvent(QTimerEvent *e) override

Detailed Description

The QChronoTimer class provides a high-level programming interface for timers. To use it, create a QChronoTimer, either passing the interval to the constructor, or setting it after construction using setInterval(), connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals. For example:

        QChronoTimer *timer = new QChronoTimer(1s, this);
        connect(timer, &QChronoTimer::timeout, this, &MyWidget::processOneThing);
        timer->start();
        QChronoTimer *timer = new QChronoTimer(this);
        connect(timer, &QChronoTimer::timeout, this, &MyWidget::processOneThing);
        timer->setInterval(1s);
        timer->start();

You can set a timer to time out only once by calling setSingleShot(true).

QChronoTimer also has singleShot() static methods:

        MyWidget widget;
        QChronoTimer::singleShot(200ms, &widget, &MyWidget::updateCaption);

In multithreaded applications, you can use QChronoTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

As a special case, a QChronoTimer with a timeout of 0ns will time out as soon as possible, though the ordering between zero timers and other sources of events is unspecified. Zero timers can be used to do some work while still providing a responsive user interface:

        // The default interval is 0ns
        QChronoTimer *timer = new QChronoTimer(this);
        connect(timer, &QChronoTimer::timeout, this, &MyWidget::processOneThing);
        timer->start();

From then on, processOneThing() will be called repeatedly. It should be written in such a way that it always returns quickly (for example, after processing one data item) so that Qt can deliver events to the user interface and stop the timer as soon as it has done all its work. This is the traditional way of implementing heavy work in GUI applications, but as multithreading is becoming available on more platforms, a modern alternative is doing the heavy work in a thread other than the GUI (main) thread. Qt has the QThread class, which can be used to achieve that.

Accuracy and Timer Resolution

The accuracy of timers depends on the underlying operating system and hardware. Most platforms support requesting nano-second precision for timers (for example, libc's nanosleep), though the accuracy of the timer will not equal this resolution in many real-world situations.

You can set the timer type to tell QChronoTimer which precision to request from the system.

For Qt::PreciseTimer, QChronoTimer will try to keep the precision at 1ns. Precise timers will never time out earlier than expected.

For Qt::CoarseTimer and Qt::VeryCoarseTimer types, QChronoTimer may wake up earlier than expected, within the margins for those types:

All timer types may time out later than expected if the system is busy or unable to provide the requested accuracy. In such a case of timeout overrun, Qt will emit timeout() only once, even if multiple timeouts have expired, and then will resume the original interval.

Alternatives to QChronoTimer

An alternative to using QChronoTimer is to call QObject::startTimer() for your object and reimplement the QObject::timerEvent() event handler in your class (which must be a sub-class of QObject). The disadvantage is that timerEvent() does not support such high-level features as single-shot timers or signals.

Another alternative is QBasicTimer. It is typically less cumbersome than using QObject::startTimer() directly. See Timers for an overview of all three approaches.

Some operating systems limit the number of timers that may be used; Qt does its best to work around these limitations.

See also QBasicTimer, QTimerEvent, QObject::timerEvent(), Timers, and Analog Clock.

Property Documentation

[bindable read-only] active : bool

Note: This property supports QProperty bindings.

This boolean property is true if the timer is running; otherwise false.

[bindable] interval : std::chrono::nanoseconds

Note: This property supports QProperty bindings.

This property holds the timeout interval

The default value for this property is 0ns.

A QChronoTimer with a timeout of 0ns will time out as soon as all the events in the window system's event queue have been processed.

Setting the interval of an active timer changes the interval and acquires a new id(). If the timer is not active, only the interval is changed.

See also singleShot.

[read-only] remainingTime : const std::chrono::nanoseconds

This property holds the remaining time

Returns the remaining duration until the timeout.

If the timer is inactive, the returned duration will be negative.

If the timer is overdue, the returned duration will be 0ns.

Access functions:

std::chrono::nanoseconds remainingTime() const

See also interval.

[bindable] singleShot : bool

Note: This property supports QProperty bindings.

This property holds whether the timer is a single-shot timer

A single-shot timer fires only once, non-single-shot timers fire every interval.

The default value for this property is false.

See also interval and singleShot().

[bindable] timerType : Qt::TimerType

Note: This property supports QProperty bindings.

Controls the accuracy of the timer

The default value for this property is Qt::CoarseTimer.

See also Qt::TimerType.

Member Function Documentation

[explicit] QChronoTimer::QChronoTimer(QObject *parent = nullptr)

Constructs a timer with the given parent, using the default interval, 0ns.

[explicit] QChronoTimer::QChronoTimer(std::chrono::nanoseconds nsec, QObject *parent = nullptr)

Constructs a timer with the given parent, using an interval of nsec.

[override virtual noexcept] QChronoTimer::~QChronoTimer()

Destroys the timer.

template <typename Functor> QMetaObject::Connection QChronoTimer::callOnTimeout(const QObject *context, Functor &&slot, Qt::ConnectionType connectionType = Qt::AutoConnection)

This function overloads callOnTimeout().

Creates a connection from the timeout() signal to slot to be placed in a specific event loop of context, with connection type connectionType, and returns a handle to the connection.

This method is provided as a convenience. It's equivalent to calling:

QObject::connect(timer, &QChronoTimer::timeout, context, slot, connectionType);

See also QObject::connect() and timeout().

Qt::TimerId QChronoTimer::id() const

Returns a Qt::TimerId representing the timer ID if the timer is running; otherwise returns Qt::TimerId::Invalid.

See also Qt::TimerId.

bool QChronoTimer::isActive() const

Returns true if the timer is running (pending); otherwise returns false.

Note: Getter function for property active.

[static] void QChronoTimer::singleShot(std::chrono::nanoseconds interval, Qt::TimerType timerType, const QObject *receiver, const char *member)

This is an overloaded function.

This static function calls the slot member, on object receiver, after time interval interval. timerType affects the precision of the timer

member has to be a member function of receiver; you need to use the SLOT() macro to get this parameter.

This function is provided as a convenience to save the need to use a timerEvent or create a local QChronoTimer object.

Note: This function is reentrant.

See also start() and Qt::TimerType.

[slot] void QChronoTimer::start()

This function overloads start().

Starts or restarts the timer with the timeout specified in interval.

If the timer is already running, it will be stopped and restarted.

If singleShot is true, the timer will be activated only once.

[slot] void QChronoTimer::stop()

Stops the timer.

See also start().

[private signal] void QChronoTimer::timeout()

This signal is emitted when the timer times out.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also interval, start(), and stop().

[override virtual protected] void QChronoTimer::timerEvent(QTimerEvent *e)

Reimplements: QObject::timerEvent(QTimerEvent *event).

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.