Skip the sleep when the job returns true - #57
Conversation
| private Closure $timeMeasure; | ||
|
|
||
| /** @param Closure(Closure):void $job */ | ||
| /** @param Closure(Closure):(bool|void) $job return true if the job did work to skip the sleep */ |
There was a problem hiding this comment.
isnt it more true|void ? :D
There was a problem hiding this comment.
Only true changes the behaviour, that's right. I'd still keep bool though, for two reasons.
false reads as an explicit "nothing to do, sleep", which makes the intent clearer than mixing return; and return true;:
$worker = DefaultWorker::create(
static function (callable $stop) use ($queue): bool {
$message = $queue->pop();
if ($message === null) {
return false; // queue is empty, sleep
}
handle($message);
return true; // there may be more, continue immediately
},
);And it lets a job pass a bool result straight through, which is common for consumer APIs:
// with bool|void
static fn (callable $stop): bool => $consumer->consumeOne();
// with true|void
static function (callable $stop) use ($consumer) {
if ($consumer->consumeOne()) {
return true;
}
};With true|void, PHPStan rejects the first closure because false is not allowed, so the result has to be converted by hand. That needs an extra branch just to drop false, and the closure can't have a native return type anymore: true|void isn't valid PHP, and true|null would throw a TypeError on the path without a return, unless you add an explicit return null.
6d0f0a5 to
558f952
Compare
A job can now return true to signal that it did work, so the next iteration starts right away. This lets queue consumers drain a full queue without pausing between messages. Any other return value keeps the regular sleep behaviour.
558f952 to
9f9b8cb
Compare
The worker always slept between iterations, even when the job just processed something and there is probably more to do. A job can now return true to say it did work, and the worker starts the next iteration right away. This is mainly for queue consumers, which can then drain a full queue without a pause after every message and only sleep once it is empty.
Only a strict true skips the sleep. Jobs returning nothing keep the current behaviour, so this is BC safe. The job type is now Closure(Closure):(bool|void).
This touches the same loop as #52, so whichever is merged second needs a small rebase.