How To Retry The Callout 3 Times Based On The Response In APEX?



In this post, we will talk about retrying the callout when receiving some defined responses like timeout error, internal server error etc. Usually, we should be prepared for these responses to accomplish the task expected after the callout smoothly.

Requirement Overview

  • To have callout 3 times based on defined response.
  • Callout should not be done frequently based on responses (Considering the callout limit).
  • At the time of specific responses, it should wait for a certain amount of time gap and then go for retry.

Solution Approach

You can approach this requirement using two apex classes .

To maintain the time interval between two callouts you can implement a Schedulable interface.

You can schedule the failure callout to retry after 5 minutes as continuous hitting can put your server flooded. (recommended)

And you are done, the below code gives a fair understanding of it.

Sample Code

Apex Class: RetryCallout 

Apex Class: ScheduleCallout

For raw code , go to the git repo here

Conclusion

By implementing the Schedulable interface, we are leveraging the scheduling mechanism for failure callout that helps us in fulfilling our requirements.

Hope you find this post useful! Catch you in next content.
And thank you for being an awesome reader.
Share and grow together !!

If you have any doubts you can comment down below, I will try to reply ASAP.

Also keep visiting us, for more such content!

Adil Ansari

Md.Adil is a Senior Salesforce developer, a Computer Science graduate working on the Salesforce platform and providing customer solutions using force.com as a Salesforce consultant/developer. He is the founder of SalesforceBitsandBytes blogging site. He shares unique real time posts on different Salesforce implementations, the source code available on this SalesforceBitsandBytes blog is fully tested in the development environment.

One thought on “How To Retry The Callout 3 Times Based On The Response In APEX?

Leave a Reply

Your email address will not be published.