Colonel Serveur
Complete Guide to Setting Up WordPress Cron Jobs

WordPress Cron Jobs are very important in the automation of scheduled tasks like posting articles, sending emails, updating plugins, and cleaning up databases. In the complete guide on how to set up WordPress Cron Jobs correctly, you will be taken through the WordPress scheduling system and how it can fail on a low-traffic WordPress site. From the guide, you will be able to set up the WordPress Cron Jobs correctly to ensure that your WordPress site runs smoothly and efficiently.

What Are WordPress Cron Jobs?

Les tâches Cron WordPress font référence au mécanisme de planification intégré du noyau WordPress qui permet au noyau WordPress d'exécuter des tâches récurrentes et ponctuelles sans avoir besoin d'accéder au mécanisme de planification des tâches cron natif du serveur.. Les tâches WordPress Cron exécutent des tâches en arrière-plan, qui incluent la publication de publications programmées, vérifier les mises à jour des plugins, envoi d'e-mails programmés, et effectuer des tâches de maintenance de routine WordPress comme le nettoyage de la base de données.

Contrairement aux tâches cron Unix traditionnelles, WordPress ne s'appuie pas sur une minuterie système pour exécuter les tâches planifiées. Plutôt, Les tâches WordPress Cron s'appuient sur l'interaction générée par les visiteurs du noyau WordPress pour exécuter des tâches planifiées.. À cet égard, WordPress vérifie si le temps d'exécution de la tâche planifiée s'est écoulé à chaque fois qu'un visiteur charge une page sur le site WordPress. Si le temps d’exécution de la tâche planifiée est écoulé, WordPress exécute la tâche planifiée pendant le processus de chargement de la page.

D'un point de vue architectural, Les tâches WordPress Cron reposent sur une combinaison de fichiers principaux, la base de données, et des hooks pour gérer les tâches planifiées. Les tâches WordPress Cron stockent les tâches planifiées sous forme d'événements dans la table wp_options de la base de données et les lient à une fonction de rappel spécifique au cœur de WordPress., plugins, et/ou thèmes fournissent.

How WordPress Cron Works Behind the Scenes

How WordPress Cron Works Behind the Scenes

Dans les coulisses, WordPress’La propre version de cron est constituée d'un fichier appelé wp-cron.php, qui est le fichier responsable de l'exécution réelle des tâches planifiées. Comme une page WordPress est demandée, WordPress compare les tâches planifiées stockées dans la base de données avec l'heure actuelle sur le serveur.

Wordpress Hosting

Hébergement Web WordPress

À partir de 3,99 $/mois

Acheter maintenant

Si un événement programmé est en attente, WordPress envoie une requête HTTP non bloquante à wp-cron.php pour chaque événement programmé. Cela signifie que ces requêtes sont exécutées de manière asynchrone, ce qui signifie qu'ils n'empêchent pas le visiteur actuel de consulter le site en attendant que les tâches planifiées soient traitées. Le fichier traite ensuite chaque événement planifié de manière séquentielle.

Quant à la programmation, cela se fait grâce à l'utilisation de hooks tels que wp_schedule_event() et wp_schedule_single_event(). Les plugins utilisent ces hooks pour planifier leurs propres tâches, qui peut être programmé pour une variété d'intervalles, comme une heure, a day, etc.

It is worth noting that WordPress Cron Jobs don’t actually execute outside of the PHP execution lifecycle, which means they are subject to a variety of PHP configuration settings, such as memory limits, execution time, etc.

Common Issues with WordPress Cron Jobs

Although WordPress Cron Jobs are very convenient, they also have some common problems that can affect the stability and performance of a website.

Some of the most common problems associated with WordPress Cron Jobs include:

  • Scheduled posts not being published due to low traffic on the website
  • Multiple cron jobs piling up and running at the same time
  • Long-running cron jobs consuming a lot of CPU resources

These problems are generally associated with the fact that the cron system relies on page views. If a website has low traffic, the scheduled tasks may not run at the same time as they are intended to. On the other hand, if a website has high traffic, the opposite problem can occur, where multiple cron jobs run at the same time.

Cheap VPS

Serveur VPS pas cher

À partir de 2,99 $/mois

Acheter maintenant

Another common problem associated with WordPress Cron Jobs is plugin conflicts. Sometimes, plugins can register cron jobs without cleaning up the database, resulting in orphaned tasks in the database even after the plugin has been uninstalled.

When You Should Use Real Cron Jobs Instead

When You Should Use Real Cron Jobs Instead

There are certain cases wherein the use of WordPress cron jobs is not encouraged, and the use of real cron jobs is preferred.

When to use real cron jobs:

  • Your WordPress site contains mission-critical cron jobs
  • Your WordPress site contains large data sets to process
  • Your WordPress site contains varying traffic patterns

The main reason to use real cron jobs is that they are executed by the operating system at a predetermined interval, which means they are more reliable and can be executed independently without any restrictions on the number of web requests that can be executed at a particular interval.

For an enterprise-level WordPress installation, it is recommended that the internal cron job mechanism should not be used, and the server-level cron job should be used instead.

Windows VPS

Hébergement VPS Windows

Remote Access & Full Admin

Acheter maintenant

How to Disable the Default WordPress Cron

The default cron system can be disabled easily by making one change to the configuration file. Adding a constant to the file will prevent WordPress cron jobs from running on page load.

Before you can set up a real cron job, il’s necessary to disable the default cron system. Running two cron systems can lead to duplicate executions of cron jobs.

By disabling the default cron system, you will no longer be running WordPress Cron Jobs. All executions of cron jobs will be handled by your server.

Setting Up a Real Cron Job on Your Server

Setting Up a Real Cron Job on Your Server

Once the internal scheduler has been disabled, the next step would be to set up a real cron job on the server. This is usually done through the hosting control panel or through SSH using crontab.

The usual setup would be to run wp-cron.php at fixed intervals, such as every 5 ou 10 minutes.

Here is a comparison between the internal cron execution and the real cron execution:

Fonctionnalité WordPress Cron Server Cron
Trigger Method Page visits OS scheduler
Fiabilité Variable Haut
Performance Impact Can spike Controlled
Best for High Traffic Non Oui

This setup gives you full control over execution timing and resource allocation.

Gestion des tâches WordPress Cron via le fichier wp-cron.php

The WordPress file that handles the execution of scheduled tasks is the wp-cron.php file. The file executes all scheduled tasks in sequence if executed directly.

Manually invoking this file by WordPress administrators helps to troubleshoot and test the execution of cron jobs. Cependant, making this file publicly accessible may pose a threat to the WordPress site.

Understanding the relationship between WordPress Cron Jobs and the file that handles the execution of scheduled tasks is crucial if you are planning to switch to server-side cron jobs or if you are experiencing execution failures.

Using WP-CLI to Control WordPress Cron Jobs

Utiliser WP-CLI pour contrôler les tâches WordPress Cron

WP-CLI can be used to efficiently manage cron jobs in WordPress. WP-CLI can be used to list cron events and the associated hooks, run overdue cron events manually, and delete cron events.

The advantages of using WP-CLI include:

  • Checking cron events and associated hooks
  • Executing overdue cron events manually
  • Deletion of cron events

The use of WP-CLI can be beneficial in situations where developers need to manage complex WordPress installations and cannot use the usual debugging tools.

Meilleures pratiques pour optimiser les tâches WordPress Cron

Optimizing WordPress Cron Jobs demands a thoughtful strategy that takes into consideration reliability, performance, and maintenance.

It is critical to conduct a review of the scheduled tasks before applying any optimizations.

The main practices in optimizing WordPress Cron Jobs include:

  • Consolidation of cron jobs
  • Increase in intervals of non-critical cron jobs
  • Offloading of heavy cron jobs

These practices will greatly reduce the server load and improve the overall responsiveness of the site.

!!!

Improper cron scheduling can negatively affect site performance. For a deeper look at speed-related optimizations, check out our complete guide to WordPress website speed optimization.

Considérations de sécurité pour les tâches Cron

Cron jobs, if misconfigured, can provide an avenue for exploitation, where the exposed cron jobs can be used to perform excessive executions, leading to denial-of-service attacks.
To be safe, it’s important to limit access to the cron execution files, ensuring that the validation of permissions takes place prior to performing any sensitive operations.

Selon le WordPress.org documentation:

“WP-Cron is triggered by visits to your site, but it can be configured to run as a real cron job for better reliability and performance.” — WordPress.org

Troubleshooting WordPress Cron Job Errors

Dépannage des erreurs de tâche WordPress Cron

In case of errors in cron jobs, some of the common signs are missing blog posts, delayed emails, and increased server loads. In order to troubleshoot WordPress cron job errors, log files are to be checked and analyzed, and the cron events are to be inspected. In order to troubleshoot cron errors, some of the common steps are checking PHP error logs, checking time zone settings, and checking the cron array in the database. Advanced debugging techniques involve manually activating WordPress Cron Jobs.

Conclusion

WordPress scheduling system, although it may seem a simple task, requires a deep understanding and implementation of the system in a professional project. Dans cet article, we learned about the WordPress cron jobs, their limitations, and when to switch from cron jobs to the real cron system. By disabling the default cron jobs, the cron server, and the WP-CLI, and keeping the security aspects in mind, you can develop a robust and scalable system as required by the search engines and the professional world.

Partager cette publication

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *