Last year, I shared how to properly setup a WordPress cron job in which I walked through the process of defining a cron job in the operating system so that a job fires as a true scheduled task (rather than the faux tasks that WordPress provides).

This isn’t to say that the native WordPress scheduled tasks are bad – they just may not work as expected for those who are used to native cron jobs.

Another limitation of the the WordPress scheduling system is that it defines only a handful of intervals in which your tasks may run. These include:

  • hourly
  • daily
  • twicedaily

And these are fine for a lot of tasks, but if you’re looking to define a new WordPress cron schedule, you’ll need to define a custom filter.

Defining a New WordPress Cron Schedule

In order to a define a new WordPress cron schedule, you need to take care of three things:

  1. Hook into the cron_schedules filter
  2. Define your interval in seconds
  3. Provide a label for your interval

For example, in a recent project, I needed to introduce a weekly interval into WordPress’ cron system. In order to do this, I needed to use the interval of 60 seconds multiplied by 60 minutes multiplied by 24 hours multiplied by 7 days which comes out to 604800 seconds.

I also wanted this to follow the normal WordPress conventions of “hourly,” “daily,” and so on, so I simply named it “weekly.”

As such, the complete function looks like this:

Notice that in the function, $schedules is an associative array in which I gave my interval the key of weekly. I then defined the value of the array as another associative array with the interval and display keys.

The interval is self-explanatory, and the display value is what will be displayed within the WordPress dashboard if you’re to take a peek at the database or if you use a plugin that displays the information of what’s setup in the scheduled tasks.

Of course, if you’re looking to define your own custom schedule (say, every two weeks), then you’d multiply the above interval by two.

Regardless, if you take the interval that you want to define, convert it seconds, and give it a label, you can hook it into the cron_schedules filter and introduce your own definition for a scheduled event. Arguably, the most important thing to consider is the key that you use in the $schedules array – if one is already defined, then you’ll overwrite it (or someone else may overwrite yours).

Category:
Notes
Tags:

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.