+ Start a Discussion
lopezclopezc 

Using Scheduled Apex jobs to do multiple call outs: Exceptions

Hi,

 

I have implemented a Scheduled job that run everyday at 6am. The apex class retrieves a few clients that match a given criteria and calls a @future method to send an email out to each of those clients. Inside the @future method the email is sent doing a call out to a third party. We do individual call outs for each client. The first call out works for the first client but the second and the rest return the following error:

 

System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

 

Does it mean that we can't do consecutive call outs within the same @future methods?

 

 

global void execute(SchedulableContext sc){
  TradeSenseEmailSender.sendTradeSenseEmail(mapOfIds);	
}

@future(Callout=true)
public static void sendTradeSenseEmail(Map<ID,ID> mapOfIds){ 
    ......
    for each clientFound{
           Http http = new Http();
 	   HttpRequest req = new HttpRequest();	  
           //Add the xml message headers               
           Map<string, string> headers = new Map<string, string>();      
           headers.put('content-length', '0');
           headers.put('Content-type','application/x-www-form-urlencoded; charset=UTF-8');
           req.setHeader('content-length', headers.get('content-length'));
           req.setHeader('Content-type', headers.get('Content-type'));
           req.setTimeout(60000);             
           req.setEndpoint(endpoint);
           req.setMethod('POST');
           req.setBody(EncodingUtil.urlEncode(xml,'UTF-8'));        
           //send the request    
           try{
              HttpResponse res = http.send(req);    
           }catch{
              System.debug(ex.getMessage());
           }  	        
    }
}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Salesforce doesn't allow you to make a callout once you have started a transaction - do you update the client to indicate the email has been sent or something along those lines?  That would explain why the first one works but not the rest.  

All Answers

bob_buzzardbob_buzzard

Salesforce doesn't allow you to make a callout once you have started a transaction - do you update the client to indicate the email has been sent or something along those lines?  That would explain why the first one works but not the rest.  

This was selected as the best answer
lopezclopezc

yes you are right, I do an insert (email sent notification)

 

thanks for the help!