Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress cron wp_schedule_single_event – action not always working

I'm registering an event like:

wp_schedule_single_event( time(), 'do_custom_hook', array( $body ) );

Above that, I have added the following action:

add_action('do_custom_hook', 'process_custom_hook', 10);

function process_custom_hook($body){
    // custom code here
}

However, sometimes the process_custom_hook function fires, while other times, it simply doesn't (it fires most times, though. It's missed about 10%-20% of the time)

The event is always returning true, meaning that it must have registered.

Also, while testing, I made sure that the arguments (body) is always different.

Any reason why this may occur?

like image 507
OhMad Avatar asked Feb 24 '20 10:02

OhMad


People also ask

Why does cron not work in WordPress?

If you're still having trouble, it's possible that your host has disabled WP Cron or prevented it from running properly. This can be the case in some managed WordPress hosting environments. If this is the case, they may have replaced it with a proper cron running on the server instead (as mentioned above).

How often should I run WP cron?

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. You will need to adjust your job if you create new schedules that need to run more frequently than every 15 minutes.

How do I know if my cron is working WordPress?

View and Control WordPress Cron System Upon activation, you need to visit Tools » Cron Events page to control cron settings. You will see a list of all cron events scheduled to run on your site using the WordPress cron system. In the first column, you will see the name of the hook that runs the cron.


1 Answers

From the codex:

Note that scheduling an event to occur before 10 minutes after an existing event of the same name will be ignored, unless you pass unique values for $args to each scheduled event.

If your custom hook is only working some of the time, then this might be an avenue to look at. If you require the hook to be handled immediately, then it might be prudent to look at giving a hook a unique name, or passing unique values to the hook.

If you do not need your job to execute immediately, then you could look at utilising wp_next_scheduled() to determine when the job will next run, and set a job to run after the next scheduled job.

It's also worth noting that if this task is something which seems to have consistent logic behind it (as seems to be the case) - why not store the job information in to the database and run a cron job every 5-10 minutes to pick up any new jobs from the database and handle them as such? This would avoid needing to deal with the behaviour of wp_schedule_single_event().

like image 110
megubyte Avatar answered Sep 19 '22 20:09

megubyte