wp-media / background-processing
异步 & 背景任务处理
Requires (Dev)
- php: ^5.6 || ^7
- brain/monkey: ^2.0
- dealerdirect/phpcodesniffer-composer-installer: ^0.5.0
- phpcompatibility/phpcompatibility-wp: ^2.0
- phpunit/phpunit: ^5.7 || ^7
- wp-coding-standards/wpcs: ^2
- wp-media/phpunit: ^1.0
This package is auto-updated.
Last update: 2024-09-22 20:43:19 UTC
README
WP Background Processing 可以用于执行非阻塞的异步请求或作为后台处理工具,允许您排队任务。
受 TechCrunch WP 异步任务 和 DeliciousBrains 启发。
需要 PHP 5.2+
异步请求
异步请求对于推送像发送邮件这样的慢速一次性任务非常有用。一旦请求被派发,它将在后台立即处理。
扩展 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();
基本认证
如果您的网站位于 BasicAuth 后面,异步请求和后台进程将无法完成。这是因为 WP Background Processing 依赖于 WordPress HTTP API,这要求您将 BasicAuth 凭据附加到请求中。最简单的方法是使用以下过滤器
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);