Apex Tip: How to keep values during Batch iterations and get the total amount of records processed on final

As you know the Apex Batch structure has 3 basic method:

  • Start : This is only executed on the first iteration before execute
  • Execute: This method runs for each scope (more info about scope here) you defined
  • Finish : this method runs after the last scope execution

Suppose now that you want to know the total amount of records processed. The natural approach to that is to have a variable and increment on each iteration, something like this:

However,  total will returns 0.  The reason of that is Apex Batch reset attributes on each iteration  :(.

The solution for that is to include the interface Database.Stateful in order to keep the variable status over the whole execution.

Finally, you’ll have something like this:

 

2 thoughts on “Apex Tip: How to keep values during Batch iterations and get the total amount of records processed on final

  1. Máximo Martínez

    Hola Martín muy buen Blog. Fui alumno tuyo en la Universidad Fasta en Ingeniería y actualmente me encuentro trabajando con SF para una empresa en Argentina. Investigando sobre un tema dí con este Blog y ¡Oh casualidad era tuyo!

    Abrazo!

    Maxi

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">