1

What is the best way to grab the last record processed in one batch? The last record needs to be marked so a new record-triggered flow can begin when the last record in one transaction ends. Thanks.

3
  • Hi and welcome to SFSE. Please take a minute to read How to Ask then edit your question to clarify what you are trying to achieve and to show what research you have done or where you are stuck with the code.
    – Phil W
    Commented Mar 24, 2022 at 8:37
  • Is it important that a specific record be marked, or just know that the batch has finished?
    – Phil W
    Commented Mar 24, 2022 at 8:38
  • Thanks for sharing the guide. I have 4 apex batch classes that are chained together. When the last record of the last transaction finishes, I wanted to run my record triggered flow. Although, it appears that batch class cannot be executed from the record-triggered flow. I just decided to chain the last class. Thanks !~~ Commented Mar 25, 2022 at 1:44

1 Answer 1

2

You can use Database.Stateful to allow instance variables to maintain state between batches (see the documentation for more details). Interestingly, static variables get reset - so you can't use those.

In you execute method, save the last record you just processed for that batch. This will get overwritten, but it will be the correct record when the finish method is called.

public class YourBatchJob implements Database.Batchable<SObject>, Database.Stateful {
    private SObject lastRecord;
    ...

    public void start(...) {
      ...
    }

    public void execute(Database.BatchableContext bc, List<SObject> scope) {
      // Do other batch stuff
      ...

      // Now remember which record was last (successfully) processed here
      lastRecord = scope[scope.size() - 1];
    }

    public void finish(Database.BatchableContext bc){
      // Do something with lastRecord 
      ...
    }
}
4
  • @FelixvanHove I am not Caspar but will take this one if that's ok. The finish method is handled on a different transaction than the last execute method one, so the variable will have its value reset without the implementation of the Stateful interface. Commented Mar 24, 2022 at 10:15
  • @FelixvanHove this is covered well in the documentation. No need to repeat it here.
    – Phil W
    Commented Mar 24, 2022 at 12:11
  • Thanks! It worked.~~ Commented Mar 25, 2022 at 1:44
  • I have a couple of other ideas, but this was by far the simplest. It should be pretty reliable, assuming that you don't get an exception in the execute method, causing it not to set the lastRecord variable. You could trap that if you wanted too. Commented Mar 25, 2022 at 1:54

You must log in to answer this question.

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