Is it possible to create a batch class that makes x calls to take n records at a time and run the dml of these records? For example. I call the service. I read the first 200 records and do dml, then call the service again, read the other 200 records and run the dml.
global class BatchCallout implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
Integer successRecords = 0;
Integer errorRecords = 0;
Integer offset = 0;
Integer maxOffset;
Boolean stopCallout = false;
String endpoint;
global BatchCallout(Integer maxOff){
maxOffset = maxOff;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
if (offset <= maxOffset){
//make callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(endpoint+'?offset='+offset);
HttpResponse res = h.send(req);
if (res.getStatus() == 200){
Map<String,Object> results = (Map<String,Object>)JSON.deserializeUntyped(res.getBody());
//increment offset
offset++;
//make DML
insert records
} else {
//make callout with same offset
//reinvoke execute method ???
}
}
}
global void finish(Database.BatchableContext BC) {
System.debug('Records success: '+successRecords);
System.debug('Records error: '+errorRecords);
} }