I recently discovered wp_schedule_single_event
which, as it sounds, allows you to schedule a one time event. This helped solved an issue I was running into while attempting to get Mailgun and Constellix talking to each other.
Automating Mailgun setup with delayed DNS verify
While working to create an automated integration with Mailgun, I ran into a situation where I needed to schedule something to run in the future. You see Mailgun requires new DNS records to be validated in order to use their service. That can be tricky to automate as DNS records take time to add and propagate.
// In 1 minute run Mailgun verify domain
wp_schedule_single_event( time() + 60, 'schedule_mailgun_verify', array( $domain ) );
The above block of code runs at the bottom of the function mailgun_setup( $domain )
and tells WordPress to run the following function in 1 minute mailgun_verify( $domain )
. The cool thing about this approach is it can be self referencing. Meaning each time the mailgun_verify
function is activated it could dynamically create future mailgun_verify
checks if needed. Here is an overview showing how it all connects.
// Mailgun setup new domain
function mailgun_setup( $domain ) {
// Do fancy Mailgun API domain setup here
// Adds Mailgun verify records to Constellix DNS
// In 1 minute run Mailgun verify domain
wp_schedule_single_event( time() + 60, 'schedule_mailgun_verify', array( $domain ) );
}
// Mailgun verify domain
function mailgun_verify( $domain ) {
// Check if records are valid.
// (TO DO: flag domain with automatic retry schedule. 60sec, 3 minutes, 6 minutes, 1hr, 24hrs)
}
// Hook to run mailgun_verify() at a later time
add_action( 'schedule_mailgun_verify', 'mailgun_verify', 10, 3 );