1

I have a plugin that creates a WP cron when activated. It runs every hour.

I need to add a simple button somewhere in the dashboard for my client, that would trigger this cron. I don't want the client to do this from plugin's interface (e.g. Cron manager), which might seem too complex for him.

Is there a native WP method or an easy way to run a specific scheduled cron?

1 Answer 1

5

When you register a scheduled event for WordPress' cron, the 3rd argument is a hook name:

wp_schedule_event( time(), 'hourly', 'my_hourly_event' );

And you add a function to run on this hook with add_action():

add_action( 'my_hourly_event', 'do_this_hourly' );

This will cause do_this_hourly() to run whenever the scheduled event runs. This works because when the scheduled time occurs, your action is called like this:

do_action( 'my_hourly_event' );

Which causes anything hooked to my_hourly_event with add_action() to run. So you can run the hooked function, like do_this_hourly(), manually at any time by just manually triggering your event with do_action(), as above, such as in response to a form submission or AJAX request.

Alternatively, you can just run the hooked function directly:

do_this_hourly();
3
  • But this will not trigger the cron - it runs the logic associated with it. Depending on the specifics of OP's question, this might suffice. However if the cron is set to run at each full hour and I manually run it at x:55, it will run again at y:00 which might not be the desired.
    – kero
    Feb 19, 2020 at 9:13
  • 1
    True, but OP didn't specify that as an issue, and this is also what the plugins they refer to do when you trigger them manually. Feb 19, 2020 at 9:20
  • 1
    I get what @kero is saying and it indeed might be a problem in some cases. However it is a sufficient solution for me, I don't know why I didn't think of this. Thanks. Feb 19, 2020 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.