6

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. The plugin should run asynchronously and doesn't hamper the functioning of the wordpress site.

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);
}
Ahwan Kumar
  • 103
  • 1
  • 7
  • If you want asynchronous, you'll probably have to go with Node.js or another alternative. PHP isn't friendly with asynchronous. [Basically the only alternative](http://php.net/manual/en/book.pthreads.php). – Brendan Nov 09 '14 at 09:26
  • Need to make this plugin for Wordpress itself and give it to bloggers so don't have an option other than PHP. – Ahwan Kumar Nov 09 '14 at 09:36
  • Again, PHP is *horrible* at this so anything you find will be a hacky workaround - but maybe [this question](http://stackoverflow.com/questions/4626860/how-can-i-run-a-php-script-in-the-background-after-a-form-is-submitted) or [this one](http://stackoverflow.com/questions/858883/run-php-task-asynchronously) will help. – Brendan Nov 09 '14 at 09:41

2 Answers2

1

Use Guzzle Package, code sample:

$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. 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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

The proper way to process asynchronous requests in WordPress is to use WP-Cron to schedule an event. 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().

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/.

doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • From the post: `The way that I handle WP-Cron on my sites is to disable it entirely by setting the DISABLE_WP_CRON constant to false in wp-config.php.`...I think you've got it backwards there. – rnevius Nov 09 '14 at 11:23