How To Setup PHP Workers
we are writing a PHP script which creates virtual machines via a RESTful API call. That part is quite easy. Once that request to create the VM is sent to the server, the API request returns with essentially "Machine queued to be created...". When we create a virt开发者_开发百科ual machine, we insert a record into a MySQL database basically with VM label, and DATE-CREATED-STARTED. That record also has a field DATE-CREATED-FINISHED which is NULL.
LABEL DATE-CREATED-STARTED DATE-CREATED-FINISHED
test-vm-1 2011-05-14 12:00:00 NULL
So here is our problem. How do we basically spin/spawn off a PHP worker, on the initial request, that checks the status of the queued virtual machine every 10 seconds, and when the virtual machine is up and running, updates DATE-CREATED-FINISHED. Keep in mind, the initial API request immediately returns "Machine queue to be created." and then exits. The PHP worker needs to be doing the 10 second check in the background.
Can your server not fire a request once the VM has been created?
Eg.
- PHP script requests the server via your API to create a new VM.
- PHP script records start time and exits. VM in queue on server waits to be created.
- Server finally creates VM and calls an update tables php script.
That way you have no polling, no cron scripts, no background threads. etc. But only if you're system can work this way. Otherwise I'd look at setting up a cron script as mentioned by @dqhendricks or if possible a background script as @Savas Alp mentioned.
If your hosting allows, create a PHP CLI program and execute it in the background like the following.
<?php
while (true)
{
sleep(10);
// Do the checks etc.
}
?>
And run it like the following command:
php background.php & // Assuming you're using Linux
If your hosting does not allow running background jobs, you must utilize every opportunity to do this check; like doing it at the beginning of every PHP page request. To help facilitate this, after creating a virtual machine, the resulting page may refresh itself at every 10 seconds!
As variant, you can use Tasks module, and there is sample of task code:
class VMCheck extends \Tasks\Task
{
protected $vm_name;
public function add($vm_name)
{
$this->getStorage()->store(__CLASS__, $vm_name, true);
}
public function execute()
{
do
{
$check = CheckAPI_call($vm_name); //your checking code here
sleep(10);
}
while (empty($check));
}
public function restore($data)
{
$this->vm_name = $data;
}
}
精彩评论