Cron Jobs and WordPress

, ,

Occasionally you find the need to have scheduled tasks run in WordPress. Ideally this should be done using WordPress Cron which allows you to tie in with visits to the website as to things being run periodically.

The main commands that you will be needing are the following commands:

wp_schedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() ). This can be used to create an event that will be repeated with time. Timestamp can be time() plus any number of seconds if you choose to schedule it in the future.  For recurrence the main string values that can be used are: ‘hourly’, ‘twicedaily’, ‘daily’, and ‘weekly’.  You can also use wp_get_schedules() to get all the schedules that have been created in your wordpress system, or you can create your own by adding a filter to the cron_schedules hook. The hook should be the name of the add_action you have created that would then fire the function you also assign.

wp_schedule_single_event( int $timestamp, string $hook, array $args = array() ) can be used to schedule an event to fire once.

wp_clear_scheduled_hook( string $hook ) can be used to clear any scheduled cron jobs from the system.

wp_next_scheduled( string $hook) can be used to see the next time an event is set to be run. If it returns an empty string then it isn't currently set to run.  So by checking the result for an empty string you can reschedule the cron job to run if it should be.

These are the main functions that can be used within a plugin to setup a cron job to fire. Allowing you to have a setting in your plugin as to whether the cron job should be on, check to see if it is on, if it isn't then schedule it to be put into the cron, and then finally turn it off.

Skills

Posted on

September 22, 2020

Submit a Comment

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