What is a cron job and how to implement it in WordPress?

What is a cron?

A cron was fist used in UNIX operating system to execute specific commands automatically on a specific time instead of executing them manually. In simple words “a cron is a time-based scheduler“.

What is a WordPress Cron?

A  WordPress cron refers to “pseudo-cron system”, WordPres cron job is a scheduled job which runs on a given time automatically.

Limitation of WordPress Cron:

WordPress cron will only run if any user visits your WordPress website’s page/post. Then WordPress will check for any available crons and execute them.

There are two types of crons in WordPress:

  1. Which runs on a specific time automatically and dies.
  2. Second, which run at a specific time automatically again and again.

A cron job may be of any type. It may be an automatic backup taking job, it may be an automatic emails sending job and list goes on depending on what you want to get done.

You can set a cron job by accessing your site’s Cpanel and it is possible some hosts might not be permitting you to set up a cron job for security reasons.

Instead of accessing crons from your site’s cPanel, you can also access crons from WordPress.

A cron job which sets up using cPanel, doesn’t need to check that visitor visits your site, cron will execute automatically at its specific time.

But, WordPress cron will only run if anyone visits your WordPress website, then WordPress checks whether the time is passed or not.

A thing to keep in mind:

“Never ever perform heavy processes in your cron job unless you have a super host like a dedicated host system with maximum performance. Otherwise, it will slow down the server.”

WordPress core and a number of plugins use WordPress Cron to execute the following tasks at regular, repeating intervals:

  1. Checking the updates for plugins and themes.
  2. Checking the WordPress version to ensure it’s up to date.
  3. Backing up the website and database.
  4. Optimizing the database to improve performance.

Below are some examples of wordpress cron jobs which fire only once at a fixed time:

  1. Sending emails at a specific time.
  2. Publishing a blog post at a specific time.

Take a look on the following code snippet:

register_activation_hook triggered when plugin is activated, and will activate our cron job. First argument of wp_schedule_event is taking the current time and the second argument is about the time interval, like daily, twice daily or hourly. And the third argument is the function hook which will actullay call the original function “do_this_hourly”.

Let us know in comments below, if it helps you with your WordPress website.

Related posts:

Leave a Reply

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