function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jerun JoseJerun Jose 

Pass value to finish method in batch apex

Hi,

 

Is there a way to be able to pass values from the execute method to the finish method.


I think this can be done using the database.stateful interface, but I do not need to maintain state of all the variables that I am using in my execute method. I only need to use one ID value which will be identified using my execute methods.

 

Please let me know if there is someway of doing this.

Best Answer chosen by Admin (Salesforce Developers) 
crop1645crop1645

The interface to finish() is defined as:

 

global void finish(Database.BatchableContext BC){}

 as this is called from SFDC, not your code.  The global variables in your batchable class provide the intercommunication 'vehicle' between start() - execute() - finish()

All Answers

SammyComesHereSammyComesHere

Try using a Static Field if you want it just for that transaction else you would have to Stateful as per my understanding. 

crop1645crop1645

This issue is covered in depth with an example in the Apex Developer's Guide in the section entitled 'Using State in Batch Apex'

 

The batchable class must also implement the DatabaseStateful interface and then you can use instance variables defined as global to maintain state. The code example shows how to do this.

 

If you look at the example, where the doc  has:

 

global Integer Summary;

 

you would replace with

 

global ID myglobalId;

 

Initialize this in the constructor, perhaps by passing it in as an argument to the constructor

Jerun JoseJerun Jose
So besides using Database.Stateful and having to manage the state persistence of all the variables that I am using, there is no simple way of just marking 1 variable to be passed to the finish method is it?
crop1645crop1645

The interface to finish() is defined as:

 

global void finish(Database.BatchableContext BC){}

 as this is called from SFDC, not your code.  The global variables in your batchable class provide the intercommunication 'vehicle' between start() - execute() - finish()

This was selected as the best answer
Jerun JoseJerun Jose
Agreed. I had to go with stateful apex. Thanks for your time