How to code auto-retry for API call

The question:

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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment