Find your content:

Search form

You are here

Apex batch for rest calls

 
Share

In my controller I have a wrapper class that gets some of its fields from case object and some from rest calls.

String query = 'some query';
List<Case> cases = Database.query(query);

for(Case c: cases) {
    CaseWrapper cWrapper = new CaseWrapper();
    cWrapper.subject = c.subject;
    cWrapper.restResult = //rest api call;
}

public class CaseWrapper {
    public String subject;
    public String restResult;
}

Now if I run this code as is I get 'Too many callouts' due to governor limits. So I am planning to use batch apex. I am very new to batch apex and I am facing this problem:

From what I have read, I think batch apex will be able to update db objects only. but I want to use batch apex to modify fields of my CaseWrapper instance. I don't persist it to db, I just convert it to json and return it to some other api. So I guess I will have to create this wrapper object inside batch apex and process it there, works for me.

but the problem is that I also want to capture in a counter variable that how many cases have been processed till now and show it to user on the associated vf page. is there a way I can do that? maybe updating some variable in my controller from the batch apex.


Attribution to: vishesh

Possible Suggestion/Solution #1

You aren't going to be able to update anything in your controller from your Batch Apex job; Batch Apex runs asynchronously and the controller will not be in scope when it runs.

What you could consider doing (and, if you're making callouts it might be preferable anyway) is run your Batch Apex with a batch size of 1. From your controller:

Id jobId = Database.executeBatch(batchInstance, 1);

And then intermittently query the AsyncApexJob object (say, every 5 seconds with some client side polling mechanism) to retrieve some information about progress:

AsyncApexJob job = [Select TotalJobItems, NumberOfErrors, JobItemsProcessed 
From AsyncApexJob Where Id = :jobId];

And then display that back to the user.


Attribution to: Phil Hawthorn
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34825

My Block Status

My Block Content