jetty-dev / background-processing
WP Background Processing可用于执行非阻塞异步请求或作为后台处理工具,允许您排队任务。
Requires
- php: >=7.1
- psr/log: ^1.1
This package is auto-updated.
Last update: 2024-09-15 01:09:54 UTC
README
WP Background Processing可用于执行非阻塞异步请求或作为后台处理工具,允许您排队任务。查看示例插件或阅读相关文章。
灵感来源于TechCrunch WP Asynchronous Tasks。
需要PHP 5.2+
安装
在项目中安装此库的推荐方式是通过Composer加载
composer require deliciousbrains/wp-background-processing
强烈建议使用Mozart包前缀包装库类文件,以防止与其他使用相同库的项目冲突。
用法
异步请求
异步请求对于将像发送电子邮件这样的慢速一次性任务推送到后台进程非常有用。一旦请求被发送,它将立即在后台处理。
扩展WP_Async_Request
类
class WP_Example_Request extends WP_Async_Request { /** * @var string */ protected $action = 'example_request'; /** * Handle * * Override this method to perform any actions required * during the async request. */ protected function handle() { // Actions to perform } }
protected $action
应设置为唯一的名称。
protected function handle()
应包含在非阻塞请求期间执行的任何逻辑。传递给请求的数据将通过$_POST
可访问。
发送请求
实例化您的请求
$this->example_request = new WP_Example_Request();
如果需要,向请求添加数据
$this->example_request->data( array( 'value1' => $value1, 'value2' => $value2 ) );
发送请求
$this->example_request->dispatch();
也支持链式调用
$this->example_request->data( array( 'data' => $data ) )->dispatch();
后台进程
后台进程与异步请求类似,但允许您排队任务。一旦队列被发送,推送到队列中的项将在后台处理。队列也会根据可用的服务器资源进行扩展,因此高端服务器将每批处理更多项。一旦一批完成,下一批将立即开始。
默认情况下,每5分钟运行一次健康检查,以确保队列在存在排队项时正在运行。如果队列失败,它将被重新启动。
队列基于先入先出原则工作,这允许即使在队列正在处理时也可以将更多项目推送到队列中。
扩展WP_Background_Process
类
class WP_Example_Process extends WP_Background_Process { /** * @var string */ protected $action = 'example_process'; /** * Task * * Override this method to perform any actions required on each * queue item. Return the modified item for further processing * in the next pass through. Or, return false to remove the * item from the queue. * * @param mixed $item Queue item to iterate over * * @return mixed */ protected function task( $item ) { // Actions to perform return false; } /** * Complete * * Override if applicable, but ensure that the below actions are * performed, or, call parent::complete(). */ protected function complete() { parent::complete(); // Show notice to user or perform some other arbitrary task... } }
protected $action
应设置为唯一的名称。
protected function task( $item )
应包含在队列项上执行的任何逻辑。返回false
以从队列中删除项,或返回$item
以将其推回队列以进行进一步处理。如果项已修改并推回队列,则在退出批处理之前将保存当前状态。
protected function complete()
可选地包含在队列完成后执行的任何逻辑。
发送进程
实例化您的进程
$this->example_process = new WP_Example_Process();
注意:您必须无条件地实例化您的进程。所有请求都应该这样做,即使没有将任何项推送到队列。
将项目推入队列
foreach ( $items as $item ) { $this->example_process->push_to_queue( $item ); }
保存并分发队列
$this->example_process->save()->dispatch();
基本认证
如果你的站点位于基本认证之后,异步请求和后台进程将无法完成。这是因为 WP 后台处理依赖于 WordPress HTTP API,它要求你在请求中附加你的基本认证凭证。最简单的方法是使用以下过滤器
function wpbp_http_request_args( $r, $url ) { $r['headers']['Authorization'] = 'Basic ' . base64_encode( USERNAME . ':' . PASSWORD ); return $r; } add_filter( 'http_request_args', 'wpbp_http_request_args', 10, 2);