这个例子演示了我如何使用 Zend_Queue 执行后台任务。在这个特定的示例中,我使用 Zend_Queue 和 cronjob 在后台生成发票,我的 Zend_Queue 被初始化并在引导程序中注册。
创建工作,My_Job 源在这里:
class My_Job_SendInvoice extends My_Job
{
protected $_invoiceId = null;
public function __construct(Zend_Queue $queue, array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
parent::__construct($queue);
}
public function job()
{
$filename = InvoiceTable::getInstance()
->generateInvoice($this->_invoiceId);
return is_file($filename);
}
}
在您的服务或模型中的某处注册工作:
$backgroundJob = new My_Job_SendInvoice(Zend_Registry::get('queue'), array(
'invoiceId' => $invoiceId
));
$backgroundJob->execute();
创建后台脚本:
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/..'));
// temp, environment should be specified prior execution
define('APPLICATION_ENV', 'development');
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
require_once 'Zend/Application.php';
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
/* @var $queue Zend_Queue */
$queue = Zend_Registry::get('queue');
$messages = $queue->receive(5);
foreach ($messages as $i => $message) {
/* @var $job My_Job */
$job = unserialize($message->body);
if ($job->job()) {
$queue->deleteMessage($message);
}
}