Blog / WordPress/ Fixing WordPress Scheduled Post Failures: Timeout Analysis & Code Solution

Fixing WordPress Scheduled Post Failures: Timeout Analysis & Code Solution

WordPress定时发布失败:超时问题分析与代码解决方案

Problem Cause: Publishing Timeout

The most common reason for WordPress scheduled posts (or future-dated posts) to fail is a timeout during the publishing request. When your site has high traffic, server load, or poor network conditions, WordPress's default, extremely short timeout (0.01 seconds) can easily cause the scheduled task to fail during background execution.

Solution: Increase the Timeout

No plugin is required. Simply add the following code to your current theme's functions.php file.

/**
 * Modify the request timeout for WordPress cron tasks.
 * @param array $arr The original cron request arguments array.
 * @return array The modified arguments array.
 */
function modify_cron_request_timeout( $arr ) {
    // Set timeout to 10 seconds
    $arr['args']['timeout'] = 10.00;
    return $arr;
}
add_filter( 'cron_request', 'modify_cron_request_timeout' );

Code Explanation & Notes

  • Function Name: The example uses a descriptive name, modify_cron_request_timeout. You can rename it to fit your naming convention.
  • Timeout Value: The code changes the timeout from the default 0.01 seconds to 10 seconds (10.00). If your server is particularly slow, you can increase this value (e.g., 30 seconds).
  • Placement: Add this code to the end of your theme's functions.php file, before the closing ?> tag if it exists. Using a child theme is recommended to prevent changes from being lost during theme updates.

How It Works

WordPress uses a system called wp-cron.php to handle scheduled tasks. When triggering a publish task, it sends an HTTP request to itself. The core code sets a very short default timeout:

wp_remote_post( $cron_url, array( 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters( 'https_local_ssl_verify', true ) ) );

The solution above uses the cron_request filter hook to intercept the request arguments array before it's sent and overwrite the timeout value from 0.01 to a more reasonable duration (like 10 seconds), giving the server adequate time to complete the publishing operation.

Other Potential Causes & Troubleshooting

If the problem persists after adjusting the timeout, check the following:

  1. Server Cron Setup: Ensure your server's system cron is correctly configured to periodically access wp-cron.php (if you have disabled WordPress's default 'pseudo-cron').
  2. Plugin Conflict: Temporarily deactivate all plugins to see if scheduled publishing works, ruling out plugin conflicts.
  3. Error Logs: Check your server's PHP error logs and WordPress debug logs for relevant error messages.

Post a Comment

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