Deferring time-consuming operations to speed up response time using asynchronous PHP in WordPress

The way PHP executes code is synchronous, which means that the operations defined in PHP are executed one after the other. If we need to perform a large number of operations in a single session, or call an external API, this synchronous execution of code can take a long time, resulting in long wait times for the user. This is a bad user experience. In this article, we'll look at how to perform time-consuming operations asynchronously.

Asynchronous Execution of PHP Tasks in WordPress with WP Cron

As we know, WordPress provides us with the WP Cron SystemThe first thing we can do is to use PHP to help us implement timed operations. The way we implement asynchronous PHP is to add some operations to a one-time task schedule after the current point in time, thus postponing operations that don't need immediate results.

For example, WordPress sends a notification email to the administrator when posting a comment, by default, this operation is performed synchronously, the email must be sent successfully before the system prompts the user to comment successfully, and on some hosts, sending the email will be slower, which leads to a longer user waiting time.

In fact, the administrator does not need to receive the notification email immediately, and even if he receives it, the administrator may not have time to deal with it immediately. Therefore, we can first prompt the user to comment successfully, and then, wait until the set time of sending email task schedule arrives, and then send the notification email.

The following function implements a simple asynchronous sending of emails:

if ( ! defined( 'DOING_CRON' ) || ( defined( 'DOING_CRON' ) && ! DOING_CRON ) ) {
   function async_send_wp_mail() {

      // Get the arguments to the wp_mail function
      $args = func_get_args();

      // Add a random value to avoid double sending, ref: http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
      $args[] = mt_rand();

      // Send the email after 5 minutes
      wp_schedule_single_event( time() + 5, 'cron_send_mail', $args ); }
   }
}

To send emails, we can use the following code to send emails asynchronously.

add_action( 'cron_send_mail', function () {
   $args = func_get_args();

   // Remove the random numbers added above
   array_pop( $args );

   call_user_func_array( 'wp_mail', $args ).
}, 10, 10 );

Asynchronous PHP operations in WordPress using WP Asynchronous Tasks library

Using WP Cron to send emails asynchronously is fairly simple, but there are some efficiency issues, and when there are more emails, the latency can be large.TechCrunch's open source WP Asynchronous Tasks The library solves this problem by adding a random number as a task marker when the task is executed, and verifying whether the task is executed successfully by this random number, and then executing the pushed-back task if it is executed successfully.

For example, on the article page, we need to fetch several articles that share a common category or tag with the current article and display them as related articles, which is a time-consuming MySQL query that we generally need to optimize using cache. When there is this data in the cache, the data in the cache will be displayed directly. If there is no such data in the cache, or the cache has expired, then fetch the data, add it to the cache, and then display it again.

This is because it is a time consuming operation on sites that are heavily browsed. If the cache is updated first and then displayed, the user waiting time may be longer. In this operation, we can use asynchronous way to optimize this operation, in the display of the page, directly display the data in the cache, and at the same time to determine the expiration of the cache, if the expiration of the cache, then add an asynchronous task to update the cache. In this way, the page will always display the cached data.

According to TechCrunch, using WP Asynchronous Tasks at the right time canImprove WordPress Page Loading SpeedTo the original 5-8 times, if your site has encountered problems in this area, you can consider using this library to optimize.

Another similar library is developed by WP Migrate DB Pro developer WP Background Processing library, which adds simple task queue support to WP Asynchronous Tasks. If we need to perform a large number of time-consuming repetitive operations, what we need may be a complete database-based WordPress Task Queue

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *