How to code auto-retry for API call

On my site I have a form that can be filled out by users. Once submitted, I am storing the form data in a third-party service using their RESTful API.

function gravity_forms_1_after_submission( $entry, $form ) {
    if ( rgar( $entry, 'status' ) === 'spam' ) {
        return;
    }

    $response = wp_remote_post(
        esc_url_raw( '...' ),
        array(
            'headers' = array(
                ...
            ),
            'body' = json_encode( array(
                ...
            ) )
        )
    );

    if ( is_wp_error( $response ) ) {
        ...
    } else {
        ...
    }
}

add_action( 'gform_after_submission_1', 'gravity_forms_1_after_submission', 10, 2 );

For cases where the API is down or there is a problem along the way, so that no data is lost, I want to code an auto-retry feature - if the first API call fails, there will be subsequent tries later until the data is successfully sent. (By subsequent tries I do not mean immediately after, since the API might be down, but maybe 5 minutes later, then 30 minutes later, then 2 hours later, until the call is successful.)

How would I go about coding that in WordPress?

Topic wp-remote-post rest-api forms Wordpress

Category Web


First you should save the data somewhere in your wordpress. I personally like to use custom tables. Then use a schedule (cron job) to check if there is new data. Then try to submit the data. If you sumitted the data successfully delete it or mark your local data as successfully submitted. Else retry it with the next schedule run. If you want to increase the waiting time with every try you could save the retry count on your local dataset.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.