In this post, we are going to show you how to use timers with Mongoose. As always, the full source code of this example is available on Github. All you need to do is to clone the repo and type “make” in the example directory.
Timers API
There is a single API function to manage timers:
double mg_set_timer(struct mg_connection *c, double timestamp);
This function schedules MG_EV_TIMER event to be delivered at timestamp time. timestamp is a UNIX time (a number of seconds since Epoch). It is C/C++ double type instead of time_t to allow for sub-second precision. This function returns the old timer value that may have been set previously.
As you can see from the mg_set_timer() signature, only a single timer may be associated with a connection. That timer can be set to any point in time. When the Mongoose event loop approaches a given time, the connection’s event handler is invoked with MG_EV_TIMER event. The event’s data is a pointer to current time and also a C double value.
Mongoose also provides a helper function to get the current time:
double mg_time(void);
How the timers example works
The timers example implements a simple HTTP server. Just before starting an event loop, we schedule the timer event to be delivered after 2.5 seconds:
// Send us MG_EV_TIMER event after 2.5 seconds
mg_set_timer(c, mg_time() + 2.5);
In the event handler, we set the timer again to be triggered after 0.5 seconds. Note, there are two mg_set_timer() calls. First call just gets the previous value of timer. It can be different from the current time, because MG_EV_TIMER can be delivered a bit later than the requested time. The second mg_set_timer() call sets the timer exactly 0.5 seconds ahead of the previous value:
case MG_EV_TIMER: {
double now = *(double *) ev_data;
double next = mg_set_timer(c, 0) + 0.5;
printf("timer event, current time: %.2lf\n", now);
// Send us timer event again after 0.5 seconds
mg_set_timer(c, next);
break;
}
And here is the output from the example. Notice, the initial 2.51 seconds interval at the beginning and subsequent 0.5 second intervals:
Starting on port 8000, time: 1467786779.25
timer event, current time: 1467786781.76
timer event, current time: 1467786782.26
timer event, current time: 1467786782.76
timer event, current time: 1467786783.25
timer event, current time: 1467786783.76
That’s it! Hope you enjoyed it.
To contact: send us a message or ask on the developer forum.