[wp-hackers] Dealing with WP cron's raciness
David Anderson
david at wordshell.net
Wed Sep 18 22:31:52 UTC 2013
Alex King wrote:
> WP-CRON uses a "run at least once" model - you need to account for
> this in your code. In our Social plugin we implemented a semaphore to
> handle the queue of things we needed to do *only once*, but that could
> take longer than the PHP timeout (multiple API calls). Feel free to
> learn from/borrow that code: https://github.com/crowdfavorite/wp-social
>
> Cheers,
> --Alex
Hi Alex,
Thank you... it's nice... a note for people finding this in Google: from
my reading and testing, I learned that your code is designed not so much
to only do the job only once, but to make sure that it can only do it
once *at the same time* (i.e. no concurrent runs). Successive runs were
possible, if the task was short-running enough and released the lock
early enough. (Which is not likely to happen with my example of a backup
job, but could happen with my other example of aggregating and
amalgamating statistics). I suppose that if that's likely to be a
problem, then the task could impose an arbitrary minimum time before
releasing the lock.
Again, for others - the relevant part of the code in the plugin that
Alex pointed to is in lib/social/semaphore.php. The simplest use case is
then this (though of course you'd want to rename the class to avoid
collisions):
$semaphore = Social_Semaphore::factory();
if ($semaphore->lock()) {
do_something();
sleep(5); # Perhaps - but it'd be more sophisticated to time
yourself and only sleep as much as needed
$semaphore->unlock();
}
David
More information about the wp-hackers
mailing list