+ Start a Discussion
Steve Berley [Left Propeller]Steve Berley [Left Propeller] 

cancel batch apex from within start method

I'm devleoping a batch apex engine that's data driven so the query string is stored in record of a custom object.

the start() method pulls the query string from the designated record of the custom object and returns it as its queryLocator.

If the start method finds that designated record has no query string, I want batch apex to quit gracefully.

How do I make this happen - form within the start method?


Amit Chaudhary 8Amit Chaudhary 8
Please check below post for Batch job related query
1) http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html

When to use Batch Apex
One example is if you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up. So in the start() method, you define the query you're going to use in this batch context: 'select Id from Account'. Then the execute() method runs, but only receives a relatively short list of records (default 200). Within the execute(), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block. Thus each time execute() is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute() is complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.

Sample Batch Apex
1) Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

2) Execute Method performs operation which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications.

NOTE:- IF queryLocator will not return any record in Start method then Execute method will not execute and directly finish method will execute

Steve Berley [Left Propeller]Steve Berley [Left Propeller]
Thank you for the reply but the question is more nuanced than obvious.  

I want to find a way to elegantly abort a batch run if the start() method recognizes an error will occur.

Why?  Rather than hard coding the query into the start() method, I'm making the start generic and storing the query as a string field in a record..  So, I need a way to bail out of batch run if a problem is discovered.