Run WordPress Cron on Real Unix Cron with Node.js

WordPress cron is a confusing beast. Most people don’t understand it or intentionally use it. It is not the same technology as Unix cron. Scheduled post functionality actually depends on WordPress cron. By default on every page load, WordPress checks to see if any cron events are due to fire. If an event is due, it sends a request to wp-cron.php asynchronously to execute the event(s).

So what?

This system works great for small websites running simple theme and plugin setups. Often when building WordPress applications for enterprise, enough resource intensive events get setup on cron that HTTP requests timeout before completion. We can circumvent this problem by executing WordPress cron using actual cron.

wp-cron-node is a simple node command that runs WordPress cron events via PHP CLI and Unix cron. It will execute WordPress cron events that are due for execution. The command requires WP-CLI.

Let’s run our scheduled events using actual Unix cron and Node:

  1. Make sure npm and WP-CLI are installed.
  2. Run the following command:

    [code language=”bash”]npm install -g wp-cron-node[/code]

  3. Disable WordPress cron. This will prevent HTTP requests from triggering cron events. Put this code in wp-config.php:

    [code language=”php”]define( ‘DISABLE_WP_CRON’, true );[/code]

  4. Finally, setup your crontab file to your liking. Edit your crontab with the following command:

    [code language=”bash”]crontab -e[/code]

    Here is an example crontab entry that will check for scheduled events every 10 minutes.

    [code language=”bash”]*/10 * * * * wp-cron-node /path/to/wp[/code]

    Note: Running this every 10 minutes means cron events could fire up to 10 minutes late. Ten is a conservative number for performance reasons. Change this to whatever makes you comfortable.


2 responses to “Run WordPress Cron on Real Unix Cron with Node.js”

  1. Does wp-cron-node run cron for each individual site on a network?

    1. No, can supply a second parameter to wp-cron-node that lets you specify the blog on the network like:
      wp-cron-node /path/to/wp

      You could write a simple bash script to call this command on each blog on the network.

Leave a Reply

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