简体   繁体   English

WP插件中的异步php代码

[英]Asynchronous php code in WP Plugin

Need to make this block of code asynchronous with the rest of the code. 需要使这段代码与其余代码异步。 Its going to collect the wp posts and send a post request to my url. 它将收集wp帖子并向我的网址发送帖子请求。 The plugin should run asynchronously and doesn't hamper the functioning of the wordpress site. 插件应该异步运行,不会妨碍wordpress站点的运行。

for ($x=0; $x<=n; $x++) {
$data = posts[$x];
$ch = curl_init('http://myurl.com/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'ACCEPT: application/json',
'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);
curl_close($ch);
}

Use Guzzle Package , code sample: 使用Guzzle Package ,代码示例:

$request = $client->createRequest('GET', ['future' => true]);
$client->send($request)->then(function ($response) {
    echo 'Got a response! ' . $response;
});

Look how can you install it . 看看你怎么安装它 Also check the RingPHP and Future Responses for some additional information. 另请参阅RingPHP和Future Responses以获取更多信息。 Actually RingPHP is utilized as the handler layer in Guzzle and at the bottom, the React/Promise is giving the Promises/A support for PHP . 实际上RingPHP被用作在处理程序层Guzzle和在底部,该反应,和/无极正在给Promises/A为支持PHP

The proper way to process asynchronous requests in WordPress is to use WP-Cron to schedule an event. 在WordPress中处理异步请求的正确方法是使用WP-Cron来安排事件。 You can either schedule it to run once, or on an interval. 您可以将其安排为运行一次,也可以按间隔运行。 See some guides on setting it up here . 请参阅一些有关在此处进行设置的指南。 The two main functions to check out are wp_schedule_event() and wp_schedule_single_event() . 签出的两个主要功能是wp_schedule_event()wp_schedule_single_event()

One thing to keep in mind however is that because your code is only running when there is a request, if there is low traffic then it's possible that your scheduled event won't run when expected. 但要记住的一件事是,因为您的代码仅在有请求时运行,如果流量较低,那么您的预定事件可能无法在预期时运行。 I wrote an article on my site regarding how you can use crontab in conjunction with WP-Cron to more accurately schedule events: http://justinsilver.com/technology/wordpress/disable-wp-cron-wordpress/ . 我在我的网站上写了一篇关于如何将crontab与WP-Cron结合使用以更准确地安排事件的文章: http//justinsilver.com/technology/wordpress/disable-wp-cron-wordpress/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM