- Qt 6.11
- Qt Core
- C++ Classes
- QChronoTimer
- Qt 6.11.1 Reference Documentation

# 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

- List of all members, including inherited members
- QChronoTimer is part of Event Classes.

## Properties

active : bool interval : std::chrono::nanoseconds remainingTime : std::chrono::nanoseconds | singleShot : bool timerType : Qt::TimerType

## 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()

## 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:

             auto *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).

Note: QChronoTimer has no singleShot() static methods, as the ones on QTimer already work with chrono types and nanoseconds resolution.

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
             QTimer *timer = new QTimer(this);
             connect(timer, &QTimer::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:

- 5% of the interval for Qt::CoarseTimer
- `500ms` for Qt::VeryCoarseTimer

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

QChronoTimer provides nanosecond resolution and a ±292 years range (less chances of integer overflow if the interval is longer than `std::numeric_limits<int>::max()`). If you only need millisecond resolution and ±24 days range, you can continue to use the classical QTimer class

Another alternative is reimplementing the QObject::timerEvent() method in your class (which must be a sub-class of QObject), and using one of the following approaches:

- Using QBasicTimer, a lightweight value-class wrapping a timer ID. You can start the timer with QBasicTimer::start() and stop it with QBasicTimer::stop(). You can handle the event in your reimplemneted timerEvent().
- A more low-level method is manipulating the timer IDs directly. To start the timer call QObject::startTimer(), storing the returned ID. To stop the timer call QObject::killTimer(). You can handle the event in your reimplemented timerEvent(). This approach is typically more cumbersome than using QBasicTimer.

A disadvantage of using timerEvent() is that some high-level features, such as single-shot timers and signals, aren't supported.

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`.

Access functions:

bool | isActive() const

### `[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 a running timer will change the interval, stop() and then start() the timer, and acquire a new id(). If the timer is not running, only the interval is changed.

Starting from Qt 6.10, setting a negative interval will result in a run-time warning and the value being reset to 1ms. Before Qt 6.10 a Qt Timer would let you set a negative interval but behave in surprising ways (for example stop the timer if it was running or not start it at all).

Access functions:

std::chrono::nanoseconds | interval() const
void | setInterval(std::chrono::nanoseconds nsec)

See also singleShot.

### `[read-only]` remainingTime : 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`.

Access functions:

bool | isSingleShot() const
void | setSingleShot(bool singleShot)

See also interval.

### `[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`.

Access functions:

Qt::TimerType | timerType() const
void | setTimerType(Qt::TimerType atype)

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)

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; otherwise returns `false`.

Note: Getter function for property active.

### `[slot]` void QChronoTimer::start()

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

If the timer is already running, it will be stopped and restarted. This will also change its id().

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).