First of all, I think you shouldn't worry about the background worker: The overhead of it idling is close to zero, but the overhead of it starting and stopping is not.
You will also run into lots of locking troubles, to avoid concurrent client requests starting up more than one
That said, here is a pattern for your use case:
- Define a flagfile and touch it on startup (this is important: File existing means worker not running)
- A client, that wants to consume your worker,
unlink()
s it, keeping the return value - If this return value is true, then this thread was the one to unlink the file, and has sort of acquired a lock on worker creation: So he creates a worker via
shell_exec()
- be carefull to start it in the background (i.e./path/to/php php -q /path/to/my_func.php &
) - The client waits for the worker to become available and submits the job
- The worker does not use the normal
while($worker->work());
loop, but a single call, then writes the flagfile and ends.