0

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.

1 Answer 1

2

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.

4
  • so if I create a constructor for batch class and pass a reference to my counter in it, will updating the counter object from batch job fail ?
    – vishesh
    Commented May 10, 2014 at 16:36
  • You can update your counter from the batch, but my point was don't use your own - use the JobItemsProcessed provided by the platform, don't try and re-invent the wheel. Commented May 10, 2014 at 16:39
  • Thanks for your answer. I am trying to learn this so I am having too many questions. Can I track the errors that occur in the batch execution, otherwise I was thinking to pass a result class in batch's constructor and use it to track errors.
    – vishesh
    Commented May 10, 2014 at 16:43
  • A common approach is to send an email in the finish method of batch apex. You can maintain state across iterations of batch apex using the Database.stateful interface. Commented May 10, 2014 at 16:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .