Home>

Most people use wordpress cron api to achieve timed tasks,Its principle is to store the created timing task into a database.When someone visits, determine whether it is time to perform this timing task.Execute if time is up.

Because of this principle,So there may be some deviations in the execution time,But as website traffic climbs and web crawlers continue to visit,Will make the timing of the execution of timing tasks more and more accurate.

If i want to create a timed task in wordpress, you usually use two functions.One of them is wp_schedule_event ()

wp_schedule_event ($timestamp, $recurrence, $hook, $args);

Such a scheduled task using this method is started,Will continue to execute,Unless you manually turn off scheduled tasks.

When you start a timed task,Difficult to debug,Because scheduled tasks are not executed every time the webpage is refreshed.In this situation,Code errors and bugs are hard to spot.

There is a way,Can help you debug.This method is to visit http://your domain name.com/wp-cron.php?doing_wp_cron, all scheduled tasks will be executed once when visiting,This can be easily debugged.

http://www.example.com/wp-cron.php?doing_wp_cron

Close a scheduled task

If i want to disable scheduled tasks,You can add the following code in wp-config.php:

/**
  * wordpress disable scheduled tasks
  * http://www.endskin.com/debug-cron/
* /
define ("disable_wp_cron", true);

Adjust execution frequency

Many people say that timing tasks have a very annoying design,That is, only three types of task execution frequencies can be set.They are hourly (performed every hour), twicedaily (performed twice a day,That is, it executes once every 12 hours) and daily (execute it every 24 hours). If i want other execution frequencies, there is no way.

Does wordpress really not support the execution frequency of custom timing tasks?the answer is negative,wordpress supports custom execution frequency of scheduled tasks,But more troublesome,Need to modify using hooks.

Below the code I added a new task execution frequency,Called weekly, the frequency of execution is once a week:

function bing_add_schedules ($schedules) {
  $schedules ["weekly"]=array (
    "interval" =>604800, //execution frequency in seconds
    "display" =>__ ("once a week") //the name displayed on the front end
  );
  return $schedules;
}
add_filter ("cron_schedules", "bing_add_schedules");

This created execution frequency can then be used on the wp_schedule_event () function:

wp_schedule_event (current_time ("timestamp"), "weekly", "test");

Summary:cron_schedules hook can add more execution frequency,To achieve the purpose of custom timing task execution frequency.

php
  • Previous jQuery implements a method to monitor all ajax requests on the page
  • Next Example of modifying PHP script to make WordPress block spam comments