+ Start a Discussion
Sunil KhuwalSunil Khuwal 

How to wait for like 30 secs between two api calls in the background.

I have a requirement, where first API callout call is made and its checking the response if the desired result is retreived, if the result is not expected, then apex code wait for 30 sec or 1 min and then again makes the api call and check again. Once the expected result is received in the API callout call. Then process stops.  All this is being happening in the background.

Solutions till now I have seen are which are currently either not working or are not correct way to do.

1. Put a while loop somewhat like this
Long startingTime = System.now().getTime(); // Num milliseconds since Jan 1 1970
            Integer delayInMilliseconds = 6000; // One-second delay
            while (System.now().getTime() - startingTime < delayInMilliseconds)  {
                // Do nothing until desired delay has passed

But this has very much chances of CPU time limit issues or it might get fail.

2. Thought of using combination of schedular and batch job, but I am unsure how to make use of this.

Can any one pls guide, how to achieve this problem statement?


SwethaSwetha (Salesforce Developers) 
HI Sunil,
Your ask seems similar to https://salesforce.stackexchange.com/questions/101154/introduce-time-delay-of-5-mins-between-http-requests .You might want to customize the below snippet as per your requirement.
==Schedulable Class==

global class scheduledCallout implements Schedulable, Database.AllowsCallouts {
    global void execute(SchedulableContext SC) {

   public static void myCallout() {
      //Do Callout here
== Calling it===

private void callInMinutes(integer minutes) {
  DateTime in10Mins = datetime.now().addMinutes(10);

  String CRON_EXP = '0 ' + in10Mins.minute() + ' ' + in10Mins.hour() + ' ' + in10Mins.day() + ' ' + in10Mins.month() + ' ? ' + dateTime.year();

 system.schedule('Callout', CRON_EXP, scheduledCallout);

If this information helps, please mark the answer as best.Thank you