Zth (libzth)
zth::PeriodicWakeUp Class Reference

Periodic wakeup after fixed interval. More...

#include <waiter.h>

Public Member Functions

 PeriodicWakeUp (TimeInterval const &interval)
 
Timestamp const & t () const noexcept
 
TimeInterval const & interval () const noexcept
 
void setInterval (TimeInterval const &interval) noexcept
 
PeriodicWakeUpoperator= (TimeInterval const &interval) noexcept
 
bool nap ()
 
bool nap (Timestamp const &reference, Timestamp const &now=Timestamp::now())
 
void operator() ()
 

Detailed Description

Periodic wakeup after fixed interval.

A common pattern is that a fiber wakes up periodically to do some work, like this:

Timestamp t = Timestamp::now();
while(true) {
do_work()
// Advance to next deadline.
t += 100_ms;
// Sleep till deadline.
nap(t);
}
If somehow the deadline is missed <i>n</i> times, because of debugging, or
some other stalled task, the loop is executed <i>n</i> times without sleeping
to catch up with t. This burst of iterations is often not required; this
missed deadlines should just be skipped.
One could be tempted to do it this way:
\code
while(true) {
do_work();
nap(100_ms);
}
Timestamp const & t() const noexcept
Definition: waiter.h:369
static Timestamp now()
Definition: time.h:554
#define catch(...)
Definition: macros.h:221

However, the sleeping may be just more than 100 ms, so the execution drifts away from a strictly 10 Hz.

Using this class, it is easier to skip missed deadlines, if it is more than one. It can be used as follows:

PeriodicWakeUp w(100_ms);
while(true) {
do_work();
// Sleep till deadline.
w();
}
PeriodicWakeUp(TimeInterval const &interval)
Definition: waiter.h:364

Definition at line 361 of file waiter.h.

Constructor & Destructor Documentation

◆ PeriodicWakeUp()

zth::PeriodicWakeUp::PeriodicWakeUp ( TimeInterval const &  interval)
inlineexplicit

Definition at line 364 of file waiter.h.

Member Function Documentation

◆ interval()

TimeInterval const& zth::PeriodicWakeUp::interval ( ) const
inlinenoexcept

Definition at line 374 of file waiter.h.

◆ nap() [1/2]

bool zth::PeriodicWakeUp::nap ( )
inline

Definition at line 390 of file waiter.h.

◆ nap() [2/2]

bool zth::PeriodicWakeUp::nap ( Timestamp const &  reference,
Timestamp const &  now = Timestamp::now() 
)

Definition at line 251 of file waiter.cpp.

◆ operator()()

void zth::PeriodicWakeUp::operator() ( )
inline

Definition at line 397 of file waiter.h.

◆ operator=()

PeriodicWakeUp& zth::PeriodicWakeUp::operator= ( TimeInterval const &  interval)
inlinenoexcept

Definition at line 384 of file waiter.h.

◆ setInterval()

void zth::PeriodicWakeUp::setInterval ( TimeInterval const &  interval)
inlinenoexcept

Definition at line 379 of file waiter.h.

◆ t()

Timestamp const& zth::PeriodicWakeUp::t ( ) const
inlinenoexcept

Definition at line 369 of file waiter.h.


The documentation for this class was generated from the following files: