Cron Job – Good Breakdown

https://uptimerobot.com/ – using this to hit wp-cron.php every 15 min

BEST FUNCTION CRON ARTICLE –

How to create a Cron Job in WordPress: Teach your plugin to do something automatically

Creating a recurring automatic function in WordPress used to be one of the most difficult things for me to understand. Several articles out there explain how to do it, yet I always forgot the concepts when the next cron job job came along. Right now it’s in my head, and that’s the time when I like to write things down for “next time”. I hope these notes will help you in your own development.

Setting up a Cron Job in WordPress involves the following items:

  1. a scheduled event, i.e. something that WordPress will execute repeatedly
  2. our own function with code to execute (we’ll hook it into the above)
  3. the event needs to be run when WordPress loads
  4. the event needs to be unscheduled upon plugin deactivation

So we’re hooking into WordPress, which gives us a new “timed hook” into which we hook our own function. No wonder this is a complex subject.

In addition, WordPress only offers three schedules, so we’ll also look into how to add our own intervals. Let’s get started.

Creating our Scheduled Event

First we’ll create a function that will schedule our event. Mine is called “mycronjob” and it will run once every day. All this code can go into your plugin’s main file, outside the main function:

[code style=”php”]
// create a scheduled event (if it does not exist already)
function cronstarter_activation() {
if( !wp_next_scheduled( ‘mycronjob’ ) ) {
wp_schedule_event( time(), ‘daily’, ‘mycronjob’ );
}
}
// and make sure it’s called whenever WordPress loads
add_action(‘wp’, ‘cronstarter_activation’);
[/code]

At the same time we want to make sure it’s unscheduled when the plugin is deactivated:
[code style=”php”]
// unschedule event upon plugin deactivation
function cronstarter_deactivate() {
// find out when the last event was scheduled
$timestamp = wp_next_scheduled (‘mycronjob’);
// unschedule previous event if any
wp_unschedule_event ($timestamp, ‘mycronjob’);
}
register_deactivation_hook (__FILE__, ‘cronstarter_deactivate’);

Now we have a hook called “mycronjob” which will be called once every day. Let’s add our own function to it:

Adding your Repeat Function
To prove that this is working we’ll send an email in this example – this is just a placeholder for your own code you’d like to run on a recurring basis:

[code style="php"]
// here’s the function we’d like to call with our cron job
function my_repeat_function() {

// do here what needs to be done automatically as per your schedule
// in this example we’re sending an email

// components for our email
$recepients = ‘you@example.com’;
$subject = ‘Hello from your Cron Job’;
$message = ‘This is a test mail sent by WordPress automatically as per your schedule.’;

// let’s send it
mail($recepients, $subject, $message);
}

// hook that function onto our scheduled event:
add_action (‘mycronjob’, ‘my_repeat_function’);

[/code]

Note how we’re adding the function to your specified event in the last line of code.

In all likelihood – and definitely for testing purposes – you may not be able to sit and wait an entire day for this email to be sent. Hence we need a more immediate schedule. Let’s tackle that next.

Creating Custom Intervals

By default, WordPress provides the following time intervals you can use:

  • daily
  • twicedaily
  • hourly

You can add your own intervals too: here’s an example in which we’re creating an interval that runs once every minute:

[code style=”php”]
// add custom interval
function cron_add_minute( $schedules ) {
// Adds once every minute to the existing schedules.
$schedules[‘everyminute’] = array(
‘interval’ => 60,
‘display’ => __( ‘Once Every Minute’ )
);
return $schedules;
}
add_filter( ‘cron_schedules’, ‘cron_add_minute’ );

[/code]

We’re adding an array called “everyminute” to the existing default intervals. You specify this in seconds and give it a display name that describes what it does.

To use this interval you need to create your scheduled event with the array name. To stick with the above example, here’s how we’d create our “mycronjob” event once every minute:

[code style=”php”]

// create a scheduled event (if it does not exist already)
function cronstarter_activation() {
if( !wp_next_scheduled( ‘mycronjob’ ) ) {
wp_schedule_event( time(), ‘everyminute’, ‘mycronjob’ );
}
}
// and make sure it’s called whenever WordPress loads
add_action(‘wp’, ‘cronstarter_activation’);

[/code]

The unschedule function remains the same as above.

Checking and Testing your Scheduled Events

Before you go on a coding spree you probably want to know if this event is actually happening as planned. I like to do this in two ways.

Setup something tangible like the email function above and set the schedule to something like once every minute. Then refresh the front page of your WordPress test instance once or twice and watch your inbox. You should receive emails more or less once a minute, if you keep refreshing the front page (not the admin page). If this works, then you’re good to go.

Another way to check if your event is recognised by WordPress is a lovely plugin by Simon Wheatly called Cron View:

http://wordpress.org/plugins/cron-view/

Once activated it will show you which events are scheduled by WordPress. Let me show you how helpful this is. The first screenshot shows a vanilla WordPress installation with its own scheduled events. “mycronjob” is nowhere to be seen (nor should it at this point):

Screen Shot 2014-01-17 at 17.11.57
Screen Shot 2014-01-17 at 17.11.57
Screen Shot 2014-01-17 at 17.11.57[/caption] Screen Shot 2014-01-17 at 17.11.57[/caption] Screen Shot 2014-01-17 at 17.11.57[/caption]

Now we’ll activate my own cron starter plugin and refresh the front page. We’ll also refresh the What’s In Cron page to see this:

Screen Shot 2014-01-17 at 17.12.34
Screen Shot 2014-01-17 at 17.12.34
Screen Shot 2014-01-17 at 17.12.34[/caption] Screen Shot 2014-01-17 at 17.12.34[/caption] Screen Shot 2014-01-17 at 17.12.34[/caption]

Just what the doctor ordered: “mycronjob” is scheduled to run in the next minute, and at the top of the screen I can see my custom schedule that have been added (Once every Minute). You can see this menu under Tools – What’s In Cron.

Thanks, Simon!

Final Thoughts

WordPress Scheduled Events are not “real” Cron Jobs, like the UNIX Cron Tab. The difference is that a “real” cron job would be reliably called by the server clock. Scheduled Events on the other hand are determined by how long ago the last event happened. If the time interval between “last run” and “right now” is larger than specified, the event fires.

This in turn relies on visitor traffic. On low or no-traffic websites like your test environment this means your event may not fire as expected. You can help this along by refreshing your front page.

Also note that traffic kicking off scheduled events can be disabled in wp-config.php by adding the following line:

define(‘DISABLE_WP_CRON’, ‘true’);

This is often done so that a “real” cron job can call the wp-cron.php file in exactly specified intervals (we’ll deal with this in another article). It’s not the default setting, but definitely something to check if your events are not working as expected.

Demo Project

I have created a demo project on GitHub that implements the above and works out of the box:

Happy Automation!


https://pantheon.io/docs/wordpress-cron

Cron for WordPress

Configuring and optimizing the WP-Cron feature on your Pantheon WordPress site.

WP-Cron Overview

WP-Cron executes specific tasks for WordPress powered sites. The name Cron comes from the Unix system for scheduling jobs, ranging from once a minute to once a year. Whether it’s routine maintenance or scheduled alerts, any command that can be executed on Unix without user intervention can be scheduled as a Cron task.

WP-Cron is similar in nature to Cron, but differs in a couple of very important ways. This feature is designed solely to handle WordPress routine tasks:

  • Check for new version of the WordPress core, themes, and plugins
  • Clean up spam

Plugins and themes can add tasks to be executed at regular intervals. For example, if you have a plugin that scans Twitter for your tweets and then incorporates them into comments, it’s most likely done with a WP-Cron job. WP-Cron opens up a whole new world of things that a WordPress powered site can do.

How is WP-Cron triggered?

The major difference between Cron and WP-Cron is how WP-Cron is triggered. Cron is a system process that runs every minute and looks for tasks to execute. WP-Cron, because it is a web-based system, can only run when someone visits the site. Therefore, when someone navigates to your WordPress site, WP-Cron checks to see if anything needs to be done. Thanks to the WordPress core developers, it does this in a way that does not adversely affect the performance of your site.

Problems With Low Traffic Sites

Low traffic WordPress sites may experience skipped tasks when this feature is triggered by visitors. If people aren’t visiting your site, WP-Cron can’t execute. This doesn’t mean your page will be slow from previous jobs when someone eventually does visit your site. Regardless of how many tasks WP-Cron has to execute, they are run in the background so your site’s performance is not adversely affected.

Problems With High Traffic Sites

If your WordPress powered site is high traffic, you may run into problems with WP-Cron. The main issues that come up are race conditions and long running processes.

  • Race condition: When more than one user visits your site and triggers WP-Cron to execute the same task. WP-Cron works hard to eliminate race conditions, but they can still happen, especially on high traffic sites.
  • Long running process: Any task that takes longer than the standard 60 seconds to run. Developers can adjust how long a PHP task is allowed to run with the set_time_limit() function. If this is set to be longer than the window between tasks, then you can end up with more than one copy of wp-cron.php executing.

Both of these issues are addressed within WP-Cron’s internal locking and are not common problems; however, they can still occasionally happen.

Manage WP-Cron Internally

WP-Cron comes preconfigured and ready to run, so you don’t need to do anything to enable it on your WordPress sites.

During the initial installation of WordPress, several tasks are automatically configured. You can use a few simple commands from the command line, or one of several plugins, to find the exact jobs being run by WP-Cron.

WP-Cron From the CLI

If you have Terminus installed, you can easily see all the details of what is going on with WP-Cron. Terminus, through WP-CLI, can show you details like:

  • What’s scheduled to run
  • What will run next
  • The event hooks that are set up

You can also schedule your own jobs, execute existing jobs, and manage just about everything WP-Cron relatedall from the command line.

One of the first things you’ll want to do is test WP-Cron to make sure everything is working correctly. When you execute the command below, make sure to replace SITE_NAME with your site’s name from your Pantheon Dashboard and replace ENV_NAME with the desired environment (“dev”, “test”, “live”, or multidev branch name).

$ terminus wp <site>.<env> -- cron test

If everything works correctly, the result looks like this:

Success: WP-Cron spawning is working as expected.

This lets you know that WP-Cron is working properly on your site. From here, you can run any cron-related command with WP-CLI. When using WP-CLI to manage your Pantheon hosted WordPress site, you should be using Terminus. The command format is as follows:

$ terminus wp <site>.<env> -- cron <your wp-cron command and switches here>

All terminus wp commands require a site name and environment to operate.

 Note

If you have protected your site using the Security setting on your Dashboard, Terminus will be unable to execute cron and you may see status report errors on the Dashboard.

Plugins

If you want to keep an eye on WP-Cron but don’t like the command line, there are several plugins you can use. WP Crontrol, for example, will show you all of the events scheduled for your site. You can create, edit, run, or delete jobs immediately from within your WordPress admin dashboard. You can also hook new actions into schedules or move existing actions to new schedules from within the Tools section.

WPX Cron Manager Lite will do a similar job with a slightly different UI. This plugin requires you to do a one-time installation of the WPX framework, which you can do straight from the plugin manager page.

Manage WP-Cron Externally

If you’re looking for more control over your site’s cron jobs, or you don’t want WP-Cron to handle tasks internally, you can use external crons instead. This will solve the problems discussed above for high traffic and low traffic sites.

Disable WP-Cron

The first thing you’ll need to do is disable WP-Cron’s internal processing. Add the following line to your wp-config.php file:

define('DISABLE_WP_CRON', true);

 Note

There are many important tasks that WP-Cron takes care of, so be prepared to complete all the steps below.

Free Services

Once you have disabled WP-Cron, you will need a service that calls a URL at regular intervals. The easiest way to do this is to set up an account with a free cron service:

Any of the above services will get the job done. By disabling WP-Cron, you have turned off the automatic checking and calling of the wp-cron.php script. You will now have to call that URL yourself using one of the services above. With most of them, it is as easy as this:

  1. Set up an account
  2. Set up a job that calls https://yourdomain.tld/wp-cron.php?doing_wp_cron

 Note

Replace `yourdomain.tld` with your domain.

Depending on what service you use, you may have the ability to set up multiple jobs at different times. Creating a single job that calls your site’s wp-cron.php script every 15 minutes is all you should need. WP-Cron will take care of the rest. If you create new schedules that need to be run more often than once every 15 minutes, you will need to adjust your job accordingly.

It’s important that you do not add a value to the doing_wp_cron query variable; it must be empty for the cron to work properly.

Using Your Own Server

If you administer your own server, you can use the cron service to make a call to the wp-cron.php script. You will have to learn how to properly set up a Cron job and use something like wget or curl to fetch a web page. Unless you take special precautions, it is not any safer to use your own server vs. a web-based cron service; however, it does give you more control.

Security

For the most part, wp-cron.php is secure. There is only one parameter you can pass in that will affect the script (doing_wp_cron). This $_GET value is not filtered; it is only used as a flag and not as input for a process or variable. Beyond that, all input is ignored.

While no script on a server attached to the Internet is 100% secure, wp-cron.php currently does not have any known vulnerabilities or exploits.

WordPress Cron Plugins

WordPress has many plugins that control both internal WP-Cron tasks and external Cron jobs. Since Pantheon does not provide Cron services, we do not recommend or discourage the use of any given plugin. We encourage you to check out the list of WordPress Cron Plugins and experiment in your Dev environment to find the one that best suits your needs.


BLUEHOST SEEMS TO BREAK NO MATTER WHAT YOU DO IF YOU DISABLE WP_CRON

BLUEHOST – CRON JOB STUFF –

https://www.bluehost.com/help/article/cron-job-basics

CRONJOB SETUP :::::::::::::::::::::::::::::::::

wget -q -O – https://the.shawneee.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

PHP command examples:
General example:
/usr/local/bin/php /home3/shawnef8/public_html/path/to/cron/script

Domain-specific example:
/usr/local/bin/ea-php73 /home3/shawnef8/domain_path/path/to/cron/script

In the above example, replace “ea-php99” with the PHP version assigned to the domain you wish to use. Look in the MultiPHP Manager for the actual PHP version assigned to a domain.

his is absurdly late to the game, but I did find a solution to this. What was happening was:

I had originally typed up the cron commands in Windows Notepad and uploaded them. Apparently what was happening was a carriage return (“/r”, IIRC) was getting plugged in, unbeknownst to me (and vim, when I viewed the file from putty.) A friend removed those carriage returns by a method I don’t recall/did not follow too well unfortunately, but after the returns were removed, it all worked.

+++++++++=======+++++++++++++++++=======+==+=+=+++++++++++++++++++++++++++

/usr/local/bin/ea-php73 /home3/shawnef8/the/wp-cron.php?doing_wp_cron

/usr/local/bin/ea-php73 /home3/shawnef8/public_html/the/wp-cron.php?doing_wp_cron

>/dev/null 2>&1 – add this and have it NOT email but track job in colder –

2ND EXAMPLE::::::::::::::::::::::::::::::::::::

Advise 1: use wget command, wget runs the PHP script exactly as if it was called from the web so the PHP environment is exactly the same of when calling the file from the web, it’s easier to debug your script then.

wget -O – https://the.shawneee.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

The cron jobs has to be created going into cPanel cron jobs menu. I don’t understand if you have this clear by reading your hoster’s answer.

And advise 2: change web hosting, try this one they don’t leave you alone.

++++++++=====++++++++++++++++++++++++++++++++++++++++++++++++

Scroll to Top