top of page
Search

Asynchronous Apex - Part 2

Batch Apex

  • Apex class must implement Database.Batchable interface, which will allow them to write code against start, execute and finish methods.

  • A batch class can be invoked by calling Database.executeBatch. It needs the instance of the class and batch size.

  • Using SOQL, status of the batch job can be monitored programmatically by querying AsyncApexJob. The same is also possible from “Apex Jobs” in setup.

  • It is used to process millions of records asynchronously.

  • Apex jobs always get executed in a separate transaction.

  • Every batch apex transactions has their own governor limit(new limit always). Thus if one batch fails, it will not impact other batches.

  • Start Method:

    • It is used to collect records or objects which will be passed to the method “execute”.

    • It returns either a Database.QueryLocator object or an Iterable.

  • Execute Method:

    • This method is responsible for doing the actual processing work.

    • Default batch size is 200.

    • Parameter it needs – a reference to Database.BatchableContext object and a list of sObjects.

  • Finish Method:

    • This method is used to do post-processing operations likes sending email etc.

You can chain a batch job by calling Database.executeBatch or System.scheduleBatch from the finish method of the current batch class. The new batch job will start after the current batch job finishes.


Scheduled Apex

  • Apex class must implement Schedulable interface. By implementing this interface, an apex class can be scheduled at specific time/day in the Apex Scheduler.

  • System.Schedule method is used to schedule an instance of the class.

  • It should implement the execute method(this is the only method). Parameter – SchedulableContext object.

  • If the class is getting scheduled from Trigger, Governor limit should be checked.

  • Once a class is scheduled, as CronTrigger object record is created. The getTriggerId method can be used to return the ID of CronTrigger record.

  • Additional processing should be done in a separate class outside of execute method.

  • Synchronous Web service callouts are not supported from scheduled apex. To do that, make an asynchronous callout in a method annotated with @future(callout=true) and then call it from scheduled apex. Note – If scheduled apex executes batch job, then callouts are possible as they are supported from batch class.

  • Maximum 100 scheduled Apex jobs at one time is possible.

 
40 views0 comments

Recent Posts

See All
bottom of page