Replacing WP Cron with a server cronjob
Normally, WordPress uses a system called WP Cron for executing certain scheduled events at regular intervals. How this works is that on every pageload, the list of scheduled actions which are currently due is checked. Any actions due to run will be executed during that pageload (after the page has finished loading).
While this usually works, it also means that an action may run much later than planned if your site does not have many visitors. Therefore we recommend setting up a cronjob on your server that runs WP Cron every minute.
This comes with several benefits:
- It ensures that any due actions are run at the correct interval.
- Your PHP CLI configuration usually has more memory and execution time at its disposal than the PHP configuration for your webserver (ie FPM or Apache).
- For Koko Analytics specifically, it ensures that stats are aggregated every minute and ample memory is available for the aggregation process.
Configuring the cronjob
The instructions below assume you are running a server based on Linux
To configure the server cronjob, SSH into your server and execute the following command to edit your server’s crontab.
* * * * * php /path/to/wordpress/wp-cron.php
The first 5 asterisks stand for the minute, hour, day of month, month and day of week respectively. Using an asterisk for each value simply means that we want to run the command that follows every minute.
Replace /path/to/wordpress/ with the path to your WordPress installation.
PS. do not worry about this running every minute. A minute is an eternity in computer time and the script will exit early if there is nothing to be done.
Checking that the cronjob runs without issues
Usually, the output of any crontab commands is sent to your system’s log file. You can verify that the cronjob configured in the step above works by issuing the following command from your server shell.
cat /var/log/syslog | grep wp-cron
If the command executes successfully, you will see an entry like this:
Sep 21 10:11:01 s1 CRON[165659]: (wordpress) CMD (php /home/wordpress/wp-cron.php )
Using WP CLI to run scheduled cron events
If you have WP CLI installed then you can use this wonderful tool to view a list of scheduled actions along with the time at which they are due:
wp cron event list
You can also use this in combination with a server cronjob to run just the koko_analytics_aggregate_stats action every minute:
wp cron event run koko_analytics_aggregate_stats