1

We wrote a batch class on a custom object "Staging_Product__c". In the batch, in the start method we are getting records as below

global Database.Querylocator start(Database.Batchablecontext BC){
   String query = 'Select Id,Name FROM Staging_Product__c WHERE Status__c=\'Pending\'';
   Database.QueryLocator ql = Database.getQueryLocator(query);

List<Staging_Product__c> mptlist = (List<Staging_Product__c>) database.query(query);
        for (Staging_Product__c mpt : mptlist) {
          mpt.Status__c = 'In Progress';
        }
        update mptlist;
   return ql;
}

We are updating the same records which are going to be processed by the batch job to In Progress so that if the second batch job based on same batch class started in parallel with first batch job doesn't pick the records which have already been picked up by the first batch job.

Does this approach okey? Does query locator keeps a local copy of queried records?

Please let me know your thoughts

1

If your batches can't run independently without accessing the same records, you could run into concurrency issues. That's when you want to look at setting parallelExecutions to false which is by default set to true. You can find a reference to this and an example of a template which contains an implementation of it in Valnavjo's Blog - Schedulable Template and Valnavjo's Blog - Batchable Template. You'll see it in the source code for the former (hosted in a gist on Github), but it's the latter post that actually shows it in use (links to the gists are in the blogs above).

I believe another option would be to look at implementing some kind of Database.Stateful interface that keeps track of what records have been processed. That's a subject that's well beyond my level of knowledge and experience to be able to share anything that might be helpful to you. I know there have been posts in the forum on the topic that you might want to search for.

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.