libfilezilla
timer_fizzbuzz.cpp

A simple demonstration of using timers.This example creates and event loop and starts two timers to print fizz and buzz every 3 respective 5 seconds.

The user can also configure a third timer via stdin to print woof.

This example assumes you already understand the events.cpp example.

#include <iostream>
#include <string>
struct interval_change_type;
class fizzbuzz final : public fz::event_handler
{
public:
fizzbuzz(fz::event_loop& loop)
: fz::event_handler(loop)
{
// Start two periodic timers
fizz_ = add_timer(fz::duration::from_seconds(3), false);
buzz_ = add_timer(fz::duration::from_seconds(5), false);
}
virtual ~fizzbuzz()
{
// This _MUST_ be called to avoid a race so that operator()(fz::event_base const&) is not called on a partially destructed object.
}
private:
virtual void operator()(fz::event_base const& ev)
{
// Dispatch the event to the correct function.
fz::dispatch<fz::timer_event, interval_change>(ev, this, &fizzbuzz::on_timer, &fizzbuzz::on_interval_change);
}
void on_interval_change(fz::duration interval)
{
// We got told to change the woof interval.
stop_timer(woof_);
woof_ = add_timer(interval, false);
}
void on_timer(fz::timer_id const& id)
{
if (id == fizz_) {
std::cout << "fizz" << std::endl;
}
else if (id == buzz_) {
std::cout << "buzz" << std::endl;
}
else if (id == woof_) {
std::cout << "woof" << std::endl;
}
}
fz::timer_id fizz_{};
fz::timer_id buzz_{};
fz::timer_id woof_{};
};
int main()
{
// Start an event loop and add a handler.
fizzbuzz fb(loop);
std::cout << "Enter interval in seconds for the woof timer or 0 to stop program." << std::endl;
// Read numbers from stdin until reading fails or a 0 is entered
int seconds;
do {
std::cin >> seconds;
if (std::cin.good() && seconds > 0) {
// Got a new interval, send to handler
fb.send_event<interval_change>(fz::duration::from_seconds(seconds));
}
}
while (std::cin.good() && seconds != 0);
return 0;
}
The duration class represents a time interval in milliseconds.
Definition: time.hpp:291
Common base class for all events.
Definition: event.hpp:23
Simple handler for asynchronous event processing.
Definition: event_handler.hpp:55
void stop_timer(timer_id id)
void remove_handler()
Deactivates handler, removes all pending events and stops all timers for this handler.
virtual void operator()(event_base const &)=0
Called by the event loop in the worker thread with the event to process.
timer_id add_timer(monotonic_clock const &deadline, duration const &interval={})
Adds a timer, returns the timer id.
A threaded event loop that supports sending events and timers.
Definition: event_loop.hpp:34
This is the recommended event class.
Definition: event.hpp:68
Declares the event_handler class.
The namespace used by libfilezilla.
Definition: apply.hpp:17
Assorted classes dealing with time.