--- libev/ev.pod 2008/09/23 09:13:59 1.185 +++ libev/ev.pod 2009/04/15 19:35:53 1.231 @@ -11,15 +11,17 @@ // a single header file is required #include + #include // for puts + // every watcher type has its own typedef'd struct - // with the name ev_ + // with the name ev_TYPE ev_io stdin_watcher; ev_timer timeout_watcher; // all watcher callbacks have a similar signature // this callback is called when data is readable on stdin static void - stdin_cb (EV_P_ struct ev_io *w, int revents) + stdin_cb (EV_P_ ev_io *w, int revents) { puts ("stdin ready"); // for one-shot events, one must manually stop the watcher @@ -32,7 +34,7 @@ // another callback, this time for a time-out static void - timeout_cb (EV_P_ struct ev_timer *w, int revents) + timeout_cb (EV_P_ ev_timer *w, int revents) { puts ("timeout"); // this causes the innermost ev_loop to stop iterating @@ -105,7 +107,7 @@ more info about various configuration options please have a look at B section in this manual. If libev was configured without support for multiple event loops, then all functions taking an initial argument of -name C (which is always of type C) will not have +name C (which is always of type C) will not have this argument. =head2 TIME REPRESENTATION @@ -216,7 +218,7 @@ See the description of C watchers for more info. -=item ev_set_allocator (void *(*cb)(void *ptr, long size)) +=item ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT] Sets the allocation function to use (the prototype is similar - the semantics are identical to the C C89/SuS/POSIX function). It is @@ -252,7 +254,7 @@ ... ev_set_allocator (persistent_realloc); -=item ev_set_syserr_cb (void (*cb)(const char *msg)); +=item ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT] Set the callback function to call on a retryable system call error (such as failed select, poll, epoll_wait). The message is a printable string @@ -278,9 +280,13 @@ =head1 FUNCTIONS CONTROLLING THE EVENT LOOP -An event loop is described by a C. The library knows two -types of such loops, the I loop, which supports signals and child -events, and dynamically created loops which do not. +An event loop is described by a C (the C +is I optional in this case, as there is also an C +I). + +The library knows two types of such loops, the I loop, which +supports signals and child events, and dynamically created loops which do +not. =over 4 @@ -296,7 +302,7 @@ Note that this function is I thread-safe, so if you want to use it from multiple threads, you have to lock (note also that this is unlikely, -as loops cannot bes hared easily between threads anyway). +as loops cannot be shared easily between threads anyway). The default loop is the only loop that can handle C and C watchers, and to do this, it always registers a handler @@ -382,26 +388,43 @@ For few fds, this backend is a bit little slower than poll and select, but it scales phenomenally better. While poll and select usually scale like O(total_fds) where n is the total number of fds (or the highest fd), -epoll scales either O(1) or O(active_fds). The epoll design has a number -of shortcomings, such as silently dropping events in some hard-to-detect -cases and requiring a system call per fd change, no fork support and bad -support for dup. +epoll scales either O(1) or O(active_fds). + +The epoll mechanism deserves honorable mention as the most misdesigned +of the more advanced event mechanisms: mere annoyances include silently +dropping file descriptors, requiring a system call per change per file +descriptor (and unnecessary guessing of parameters), problems with dup and +so on. The biggest issue is fork races, however - if a program forks then +I parent and child process have to recreate the epoll set, which can +take considerable time (one syscall per file descriptor) and is of course +hard to detect. + +Epoll is also notoriously buggy - embedding epoll fds I work, but +of course I, and epoll just loves to report events for totally +I file descriptors (even already closed ones, so one cannot +even remove them from the set) than registered in the set (especially +on SMP systems). Libev tries to counter these spurious notifications by +employing an additional generation counter and comparing that against the +events to filter out spurious ones, recreating the set when required. While stopping, setting and starting an I/O watcher in the same iteration -will result in some caching, there is still a system call per such incident -(because the fd could point to a different file description now), so its -best to avoid that. Also, C'ed file descriptors might not work -very well if you register events for both fds. - -Please note that epoll sometimes generates spurious notifications, so you -need to use non-blocking I/O or other means to avoid blocking when no data -(or space) is available. +will result in some caching, there is still a system call per such +incident (because the same I could point to a different +I now), so its best to avoid that. Also, C'ed +file descriptors might not work very well if you register events for both +file descriptors. Best performance from this backend is achieved by not unregistering all watchers for a file descriptor until it has been closed, if possible, i.e. keep at least one watcher active per fd at all times. Stopping and starting a watcher (without re-setting it) also usually doesn't cause -extra overhead. +extra overhead. A fork can both result in spurious notifications as well +as in libev having to destroy and recreate the epoll object, which can +take considerable time and thus should be avoided. + +All this means that, in practice, C can be as fast or +faster than epoll for maybe up to a hundred file descriptors, depending on +the usage. So sad. While nominally embeddable in other event loops, this feature is broken in all kernel versions tested so far. @@ -411,12 +434,15 @@ =item C (value 8, most BSD clones) -Kqueue deserves special mention, as at the time of this writing, it was -broken on all BSDs except NetBSD (usually it doesn't work reliably with -anything but sockets and pipes, except on Darwin, where of course it's -completely useless). For this reason it's not being "auto-detected" unless -you explicitly specify it in the flags (i.e. using C) or -libev was compiled on a known-to-be-good (-enough) system like NetBSD. +Kqueue deserves special mention, as at the time of this writing, it +was broken on all BSDs except NetBSD (usually it doesn't work reliably +with anything but sockets and pipes, except on Darwin, where of course +it's completely useless). Unlike epoll, however, whose brokenness +is by design, these kqueue bugs can (and eventually will) be fixed +without API changes to existing programs. For this reason it's not being +"auto-detected" unless you explicitly specify it in the flags (i.e. using +C) or libev was compiled on a known-to-be-good (-enough) +system like NetBSD. You still can embed kqueue into a normal poll or select backend and use it only for sockets (after having made sure that sockets work with kqueue on @@ -426,8 +452,9 @@ kernel is more efficient (which says nothing about its actual speed, of course). While stopping, setting and starting an I/O watcher does never cause an extra system call as with C, it still adds up to -two event changes per incident. Support for C is very bad and it -drops fds silently in similarly hard-to-detect cases. +two event changes per incident. Support for C is very bad (but +sane, unlike epoll) and it drops fds silently in similarly hard-to-detect +cases This backend usually performs well under most conditions. @@ -435,8 +462,8 @@ everywhere, so you might need to test for this. And since it is broken almost everywhere, you should only use it when you have a lot of sockets (for which it usually works), by embedding it into another event loop -(e.g. C or C) and, did I mention it, -using it only for sockets. +(e.g. C or C (but C is of course +also broken on OS X)) and, did I mention it, using it only for sockets. This backend maps C into an C kevent with C, and C into an C kevent with @@ -466,7 +493,7 @@ On the positive side, with the exception of the spurious readiness notifications, this backend actually performed fully to specification in all tests and is fully embeddable, which is a rare feat among the -OS-specific backends. +OS-specific backends (I vastly prefer correctness over speed hacks). This backend maps C and C in the same way as C. @@ -529,9 +556,9 @@ the easiest thing, you can just ignore the watchers and/or C them for example). -Note that certain global state, such as signal state, will not be freed by -this function, and related watchers (such as signal and child watchers) -would need to be stopped manually. +Note that certain global state, such as signal state (and installed signal +handlers), will not be freed by this function, and related watchers (such +as signal and child watchers) would need to be stopped manually. In general it is not advisable to call this function except in the rare occasion where you really need to free e.g. the signal handling @@ -609,6 +636,32 @@ See also "The special problem of time updates" in the C section. +=item ev_suspend (loop) + +=item ev_resume (loop) + +These two functions suspend and resume a loop, for use when the loop is +not used for a while and timeouts should not be processed. + +A typical use case would be an interactive program such as a game: When +the user presses C<^Z> to suspend the game and resumes it an hour later it +would be best to handle timeouts as if no time had actually passed while +the program was suspended. This can be achieved by calling C +in your C handler, sending yourself a C and calling +C directly afterwards to resume timer processing. + +Effectively, all C watchers will be delayed by the time spend +between C and C, and all C watchers +will be rescheduled (that is, they will lose any events that would have +occured while suspended). + +After calling C you B call I function on the +given loop other than C, and you B call C +without a previous call to C. + +Calling C/C has the side effect of updating the +event loop time (see C). + =item ev_loop (loop, int flags) Finally, this is it, the event handler. This function usually is called @@ -633,7 +686,7 @@ A flags value of C will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block your process until at least one new event arrives (which could -be an event internal to libev itself, so there is no guarentee that a +be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop. @@ -687,6 +740,8 @@ This "unloop state" will be cleared when entering C again. +It is safe to call C from otuside any C calls. + =item ev_ref (loop) =item ev_unref (loop) @@ -699,18 +754,20 @@ from returning, call ev_unref() after starting, and ev_ref() before stopping it. -As an example, libev itself uses this for its internal signal pipe: It is -not visible to the libev user and should not keep C from exiting -if no event watchers registered by it are active. It is also an excellent -way to do this for generic recurring timers or from within third-party -libraries. Just remember to I and I -(but only if the watcher wasn't active before, or was active before, -respectively). +As an example, libev itself uses this for its internal signal pipe: It +is not visible to the libev user and should not keep C from +exiting if no event watchers registered by it are active. It is also an +excellent way to do this for generic recurring timers or from within +third-party libraries. Just remember to I and I (but only if the watcher wasn't active before, or was active +before, respectively. Note also that libev might stop watchers itself +(e.g. non-repeating timers) in which case you have to C +in the callback). Example: Create a signal watcher, but keep it from keeping C running when nothing else is active. - struct ev_signal exitsig; + ev_signal exitsig; ev_signal_init (&exitsig, sig_cb, SIGINT); ev_signal_start (loop, &exitsig); evf_unref (loop); @@ -768,7 +825,7 @@ =item ev_loop_verify (loop) This function only does something when C support has been -compiled in. which is the default for non-minimal builds. It tries to go +compiled in, which is the default for non-minimal builds. It tries to go through all internal structures and checks them for validity. If anything is found to be inconsistent, it will print an error message to standard error and call C. @@ -782,26 +839,36 @@ =head1 ANATOMY OF A WATCHER +In the following description, uppercase C in names stands for the +watcher type, e.g. C can mean C for timer +watchers and C for I/O watchers. + A watcher is a structure that you create and register to record your interest in some event. For instance, if you want to wait for STDIN to become readable, you would create an C watcher for that: - static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) + static void my_cb (struct ev_loop *loop, ev_io *w, int revents) { ev_io_stop (w); ev_unloop (loop, EVUNLOOP_ALL); } struct ev_loop *loop = ev_default_loop (0); - struct ev_io stdin_watcher; + + ev_io stdin_watcher; + ev_init (&stdin_watcher, my_cb); ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); ev_io_start (loop, &stdin_watcher); + ev_loop (loop, 0); As you can see, you are responsible for allocating the memory for your -watcher structures (and it is usually a bad idea to do this on the stack, -although this can sometimes be quite valid). +watcher structures (and it is I a bad idea to do this on the +stack). + +Each watcher has an associated watcher structure (called C +or simply C, as typedefs are provided for all watcher structs). Each watcher structure must be initialised by a call to C, which expects a callback to be provided. This @@ -809,19 +876,19 @@ watchers, each time the event loop detects that the file descriptor given is readable and/or writable). -Each watcher type has its own C<< ev__set (watcher *, ...) >> macro -with arguments specific to this watcher type. There is also a macro -to combine initialisation and setting in one call: C<< ev__init -(watcher *, callback, ...) >>. +Each watcher type further has its own C<< ev_TYPE_set (watcher *, ...) >> +macro to configure it, with arguments specific to the watcher type. There +is also a macro to combine initialisation and setting in one call: C<< +ev_TYPE_init (watcher *, callback, ...) >>. To make the watcher actually watch out for events, you have to start it -with a watcher-specific start function (C<< ev__start (loop, watcher +with a watcher-specific start function (C<< ev_TYPE_start (loop, watcher *) >>), and you can stop watching for events at any time by calling the -corresponding stop function (C<< ev__stop (loop, watcher *) >>. +corresponding stop function (C<< ev_TYPE_stop (loop, watcher *) >>. As long as your watcher is active (has been started but not stopped) you must not touch the values stored in it. Most specifically you must never -reinitialise it or call its C macro. +reinitialise it or call its C macro. Each and every callback receives the event loop pointer as first, the registered watcher structure as second, and a bitset of received events as @@ -889,13 +956,22 @@ The given async watcher has been asynchronously notified (see C). +=item C + +Not ever sent (or otherwise used) by libev itself, but can be freely used +by libev users to signal watchers (e.g. via C). + =item C An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because libev ran out of memory, a file descriptor was found to be closed or any other -problem. You best act on it by reporting the problem and somehow coping -with the watcher being stopped. +problem. Libev considers these application bugs. + +You best act on it by reporting the problem and somehow coping with the +watcher being stopped. Note that well-written programs should not receive +an error ever, so when your watcher receives it, this usually indicates a +bug in your program. Libev will usually signal a few "dummy" events together with an error, for example it might indicate that a fd is readable or writable, and if your @@ -908,9 +984,6 @@ =head2 GENERIC WATCHER FUNCTIONS -In the following description, C stands for the watcher type, -e.g. C for C watchers and C for C watchers. - =over 4 =item C (ev_TYPE *watcher, callback) @@ -925,7 +998,7 @@ You can reinitialise a watcher at any time as long as it has been stopped (or never started) and there are no pending events outstanding. -The callback is always of type C. Example: Initialise an C watcher in two steps. @@ -969,12 +1042,14 @@ =item C (loop *, ev_TYPE *watcher) -Stops the given watcher again (if active) and clears the pending -status. It is possible that stopped watchers are pending (for example, -non-repeating timers are being stopped when they become pending), but -C ensures that the watcher is neither active nor pending. If -you want to free or reuse the memory used by the watcher it is therefore a -good idea to always call its C function. +Stops the given watcher if active, and clears the pending status (whether +the watcher was active or not). + +It is possible that stopped watchers are pending - for example, +non-repeating timers are being stopped when they become pending - but +calling C ensures that the watcher is neither active nor +pending. If you want to free or reuse the memory used by the watcher it is +therefore a good idea to always call its C function. =item bool ev_is_active (ev_TYPE *watcher) @@ -1026,7 +1101,7 @@ Setting a priority outside the range of C to C is fine, as long as you do not mind that the priority value you query might -or might not have been adjusted to be within valid range. +or might not have been clamped to the valid range. =item ev_invoke (loop, ev_TYPE *watcher, int revents) @@ -1058,7 +1133,7 @@ struct my_io { - struct ev_io io; + ev_io io; int otherfd; void *somedata; struct whatever *mostinteresting; @@ -1071,7 +1146,7 @@ And since your callback will be called with a pointer to the watcher, you can cast it back to your own type: - static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) + static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) { struct my_io *w = (struct my_io *)w_; ... @@ -1099,14 +1174,14 @@ #include static void - t1_cb (EV_P_ struct ev_timer *w, int revents) + t1_cb (EV_P_ ev_timer *w, int revents) { struct my_biggy big = (struct my_biggy * (((char *)w) - offsetof (struct my_biggy, t1)); } static void - t2_cb (EV_P_ struct ev_timer *w, int revents) + t2_cb (EV_P_ ev_timer *w, int revents) { struct my_biggy big = (struct my_biggy * (((char *)w) - offsetof (struct my_biggy, t2)); @@ -1251,7 +1326,7 @@ attempt to read a whole line in the callback. static void - stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) + stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents) { ev_io_stop (loop, w); .. read from stdin here (or from w->fd) and handle any I/O errors @@ -1259,7 +1334,7 @@ ... struct ev_loop *loop = ev_default_init (0); - struct ev_io stdin_readable; + ev_io stdin_readable; ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); ev_io_start (loop, &stdin_readable); ev_loop (loop, 0); @@ -1277,8 +1352,185 @@ monotonic clock option helps a lot here). The callback is guaranteed to be invoked only I its timeout has -passed, but if multiple timers become ready during the same loop iteration -then order of execution is undefined. +passed. If multiple timers become ready during the same loop iteration +then the ones with earlier time-out values are invoked before ones with +later time-out values (but this is no longer true when a callback calls +C recursively). + +=head3 Be smart about timeouts + +Many real-world problems involve some kind of timeout, usually for error +recovery. A typical example is an HTTP request - if the other side hangs, +you want to raise some error after a while. + +What follows are some ways to handle this problem, from obvious and +inefficient to smart and efficient. + +In the following, a 60 second activity timeout is assumed - a timeout that +gets reset to 60 seconds each time there is activity (e.g. each time some +data or other life sign was received). + +=over 4 + +=item 1. Use a timer and stop, reinitialise and start it on activity. + +This is the most obvious, but not the most simple way: In the beginning, +start the watcher: + + ev_timer_init (timer, callback, 60., 0.); + ev_timer_start (loop, timer); + +Then, each time there is some activity, C it, initialise it +and start it again: + + ev_timer_stop (loop, timer); + ev_timer_set (timer, 60., 0.); + ev_timer_start (loop, timer); + +This is relatively simple to implement, but means that each time there is +some activity, libev will first have to remove the timer from its internal +data structure and then add it again. Libev tries to be fast, but it's +still not a constant-time operation. + +=item 2. Use a timer and re-start it with C inactivity. + +This is the easiest way, and involves using C instead of +C. + +To implement this, configure an C with a C value +of C<60> and then call C at start and each time you +successfully read or write some data. If you go into an idle state where +you do not expect data to travel on the socket, you can C +the timer, and C will automatically restart it if need be. + +That means you can ignore both the C function and the +C argument to C, and only ever use the C +member and C. + +At start: + + ev_timer_init (timer, callback); + timer->repeat = 60.; + ev_timer_again (loop, timer); + +Each time there is some activity: + + ev_timer_again (loop, timer); + +It is even possible to change the time-out on the fly, regardless of +whether the watcher is active or not: + + timer->repeat = 30.; + ev_timer_again (loop, timer); + +This is slightly more efficient then stopping/starting the timer each time +you want to modify its timeout value, as libev does not have to completely +remove and re-insert the timer from/into its internal data structure. + +It is, however, even simpler than the "obvious" way to do it. + +=item 3. Let the timer time out, but then re-arm it as required. + +This method is more tricky, but usually most efficient: Most timeouts are +relatively long compared to the intervals between other activity - in +our example, within 60 seconds, there are usually many I/O events with +associated activity resets. + +In this case, it would be more efficient to leave the C alone, +but remember the time of last activity, and check for a real timeout only +within the callback: + + ev_tstamp last_activity; // time of last activity + + static void + callback (EV_P_ ev_timer *w, int revents) + { + ev_tstamp now = ev_now (EV_A); + ev_tstamp timeout = last_activity + 60.; + + // if last_activity + 60. is older than now, we did time out + if (timeout < now) + { + // timeout occured, take action + } + else + { + // callback was invoked, but there was some activity, re-arm + // the watcher to fire in last_activity + 60, which is + // guaranteed to be in the future, so "again" is positive: + w->repeat = timeout - now; + ev_timer_again (EV_A_ w); + } + } + +To summarise the callback: first calculate the real timeout (defined +as "60 seconds after the last activity"), then check if that time has +been reached, which means something I, in fact, time out. Otherwise +the callback was invoked too early (C is in the future), so +re-schedule the timer to fire at that future time, to see if maybe we have +a timeout then. + +Note how C is used, taking advantage of the +C optimisation when the timer is already running. + +This scheme causes more callback invocations (about one every 60 seconds +minus half the average time between activity), but virtually no calls to +libev to change the timeout. + +To start the timer, simply initialise the watcher and set C +to the current time (meaning we just have some activity :), then call the +callback, which will "do the right thing" and start the timer: + + ev_timer_init (timer, callback); + last_activity = ev_now (loop); + callback (loop, timer, EV_TIMEOUT); + +And when there is some activity, simply store the current time in +C, no libev calls at all: + + last_actiivty = ev_now (loop); + +This technique is slightly more complex, but in most cases where the +time-out is unlikely to be triggered, much more efficient. + +Changing the timeout is trivial as well (if it isn't hard-coded in the +callback :) - just change the timeout and invoke the callback, which will +fix things for you. + +=item 4. Wee, just use a double-linked list for your timeouts. + +If there is not one request, but many thousands (millions...), all +employing some kind of timeout with the same timeout value, then one can +do even better: + +When starting the timeout, calculate the timeout value and put the timeout +at the I of the list. + +Then use an C to fire when the timeout at the I of +the list is expected to fire (for example, using the technique #3). + +When there is some activity, remove the timer from the list, recalculate +the timeout, append it to the end of the list again, and make sure to +update the C if it was taken from the beginning of the list. + +This way, one can manage an unlimited number of timeouts in O(1) time for +starting, stopping and updating the timers, at the expense of a major +complication, and having to use a constant timeout. The constant timeout +ensures that the list stays sorted. + +=back + +So which method the best? + +Method #2 is a simple no-brain-required solution that is adequate in most +situations. Method #3 requires a bit more thinking, but handles many cases +better, and isn't very complicated either. In most case, choosing either +one is fine, with #3 being better in typical situations. + +Method #1 is almost always a bad idea, and buys you nothing. Method #4 is +rather complicated, but extremely efficient, something that really pays +off after the first million or so of active timers, i.e. it's usually +overkill :) =head3 The special problem of time updates @@ -1332,36 +1584,8 @@ If the timer is repeating, either start it if necessary (with the C value), or reset the running timer to the C value. -This sounds a bit complicated, but here is a useful and typical -example: Imagine you have a TCP connection and you want a so-called idle -timeout, that is, you want to be called when there have been, say, 60 -seconds of inactivity on the socket. The easiest way to do this is to -configure an C with a C value of C<60> and then call -C each time you successfully read or write some data. If -you go into an idle state where you do not expect data to travel on the -socket, you can C the timer, and C will -automatically restart it if need be. - -That means you can ignore the C value and C -altogether and only ever use the C value and C: - - ev_timer_init (timer, callback, 0., 5.); - ev_timer_again (loop, timer); - ... - timer->again = 17.; - ev_timer_again (loop, timer); - ... - timer->again = 10.; - ev_timer_again (loop, timer); - -This is more slightly efficient then stopping/starting the timer each time -you want to modify its timeout value. - -Note, however, that it is often even more efficient to remember the -time of the last activity and let the timer time-out naturally. In the -callback, you then check whether the time-out is real, or, if there was -some activity, you reschedule the watcher to time-out in "last_activity + -timeout - ev_now ()" seconds. +This sounds a bit complicated, see "Be smart about timeouts", above, for a +usage example. =item ev_tstamp repeat [read-write] @@ -1376,12 +1600,12 @@ Example: Create a timer that fires after 60 seconds. static void - one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) + one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents) { .. one minute over, w is actually stopped right here } - struct ev_timer mytimer; + ev_timer mytimer; ev_timer_init (&mytimer, one_minute_cb, 60., 0.); ev_timer_start (loop, &mytimer); @@ -1389,12 +1613,12 @@ inactivity. static void - timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) + timeout_cb (struct ev_loop *loop, ev_timer *w, int revents) { .. ten seconds without any activity } - struct ev_timer mytimer; + ev_timer mytimer; ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ ev_timer_again (&mytimer); /* start timer */ ev_loop (loop, 0); @@ -1409,52 +1633,63 @@ Periodic watchers are also timers of a kind, but they are very versatile (and unfortunately a bit complex). -Unlike C's, they are not based on real time (or relative time) -but on wall clock time (absolute time). You can tell a periodic watcher -to trigger after some specific point in time. For example, if you tell a -periodic watcher to trigger in 10 seconds (by specifying e.g. C, that is, an absolute time not a delay) and then reset your system -clock to January of the previous year, then it will take more than year -to trigger the event (unlike an C, which would still trigger -roughly 10 seconds later as it uses a relative timeout). - -Cs can also be used to implement vastly more complex timers, -such as triggering an event on each "midnight, local time", or other -complicated rules. +Unlike C, periodic watchers are not based on real time (or +relative time, the physical time that passes) but on wall clock time +(absolute time, the thing you can read on your calender or clock). The +difference is that wall clock time can run faster or slower than real +time, and time jumps are not uncommon (e.g. when you adjust your +wrist-watch). + +You can tell a periodic watcher to trigger after some specific point +in time: for example, if you tell a periodic watcher to trigger "in 10 +seconds" (by specifying e.g. C, that is, an absolute time +not a delay) and then reset your system clock to January of the previous +year, then it will take a year or more to trigger the event (unlike an +C, which would still trigger roughly 10 seconds after starting +it, as it uses a relative timeout). + +C watchers can also be used to implement vastly more complex +timers, such as triggering an event on each "midnight, local time", or +other complicated rules. This cannot be done with C watchers, as +those cannot react to time jumps. As with timers, the callback is guaranteed to be invoked only when the -time (C) has passed, but if multiple periodic timers become ready -during the same loop iteration, then order of execution is undefined. +point in time where it is supposed to trigger has passed. If multiple +timers become ready during the same loop iteration then the ones with +earlier time-out values are invoked before ones with later time-out values +(but this is no longer true when a callback calls C recursively). =head3 Watcher-Specific Functions and Data Members =over 4 -=item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb) +=item ev_periodic_init (ev_periodic *, callback, ev_tstamp offset, ev_tstamp interval, reschedule_cb) -=item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb) +=item ev_periodic_set (ev_periodic *, ev_tstamp offset, ev_tstamp interval, reschedule_cb) -Lots of arguments, lets sort it out... There are basically three modes of +Lots of arguments, let's sort it out... There are basically three modes of operation, and we will explain them from simplest to most complex: =over 4 -=item * absolute timer (at = time, interval = reschedule_cb = 0) +=item * absolute timer (offset = absolute time, interval = 0, reschedule_cb = 0) In this configuration the watcher triggers an event after the wall clock -time C has passed. It will not repeat and will not adjust when a time -jump occurs, that is, if it is to be run at January 1st 2011 then it will -only run when the system clock reaches or surpasses this time. +time C has passed. It will not repeat and will not adjust when a +time jump occurs, that is, if it is to be run at January 1st 2011 then it +will be stopped and invoked when the system clock reaches or surpasses +this point in time. -=item * repeating interval timer (at = offset, interval > 0, reschedule_cb = 0) +=item * repeating interval timer (offset = offset within interval, interval > 0, reschedule_cb = 0) In this mode the watcher will always be scheduled to time out at the next -C time (for some integer N, which can also be negative) -and then repeat, regardless of any time jumps. +C time (for some integer N, which can also be +negative) and then repeat, regardless of any time jumps. The C +argument is merely an offset into the C periods. This can be used to create timers that do not drift with respect to the -system clock, for example, here is a C that triggers each -hour, on the hour: +system clock, for example, here is an C that triggers each +hour, on the hour (with respect to UTC): ev_periodic_set (&periodic, 0., 3600., 0); @@ -1465,9 +1700,9 @@ Another way to think about it (for the mathematically inclined) is that C will try to run the callback in this mode at the next possible -time where C