19

I have a requirement where I need to process a list of string having hundreds of records in it . For each string I need to have an http callout so I cant run in a normal apex method. For this I am trying to pass the list to a batch apex class and then execute each callout in the execute method so that I wont hit the callout limit. Here is my problem the start method can return only Database.querylocator or Database.iterable. How to pass a list string from the start method with a specified batch size? below is the code explaining the same

 global  class DF_BatchToExcessFields implements Database.Batchable<sObject>{
global list<String> batchlist = new list<String>();

global DF_BatchToExcessFields(list<String> lstObjectAsString)
    {
        batchlist.addAll(lstObjectAsString);
    }

    global Iterable<sObject> start(Database.BatchableContext info){ 

            //Current code
           //str='select id from account';  // just a query for start method
           // return  Database.getQueryLocator(str);

           // My requiremnt is to pass part of list batchlist  to execute method
    }     
    global void execute(Database.BatchableContext info, List<account> scope){
              //I want to process the string ie http callout here

    }     
    global void finish(Database.BatchableContext info){     
    } 
}
26

All lists are iterables. Create a constructor to take the list, and change the interface of your class:

global class DF_BatchToExcessFields implements Database.Batchable<String> {...

Then return the list in the Start method. Here's a great article by AFawcett to help you get the idea:

http://andyinthecloud.com/2013/08/11/batch-worker-getting-more-done-with-less-work/

Iterable<String> i = new List<String> { 'A', 'B', 'C' };

public with sharing class SimpleBatchApex implements Database.Batchable<String> {
    public Iterable<String> start(Database.BatchableContext BC) {
        return new List<String> { 'Do something', 'Do something else', 'And something more' };
    }

    public void execute(Database.BatchableContext info, List<String> strings) {
        // Do something really expensive with the string!
        String myString = strings[0];
    }

    public void finish(Database.BatchableContext info) {}
}

then try it out in Developer Console

//Process the String's one by one each with its own governor context
Id jobId = Database.executeBatch(new SimpleBatchApex(), 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.