Ways to mix Asynchronous Apex without issues

Introduction

“Future method cannot be called from a future or batch method” or “Database.executeBatch cannot be called from a batch start, batch execute, or future method”… Sounds familiar? Queueable, Future, Batch, Schedule… How often do you think about what approach you should take to avoid such problems? No more doubts!

Solution

Here is an easy-to-use guide that will solve your problems with mixing Asynchronous Apex once and for all:

Asynchronous Apex table

A high-level overview of each Asynchronous Apex

Future Methods

  • run in their own thread, and do not start until resources are available
  • when to use:
    • when you have a long-running method and need to prevent delaying an Apex transaction
    • when you make callouts to external Web services
    • to segregate DML operations and bypass the mixed save DML error
  • common scenarios:
    • web service callout

Queueable Apex

  • similar to future methods, but provide additional job chaining and allow more complex data types to be used
  • when to use:
    • to start a long-running operation and get an ID for it
    • to pass complex types to a job
    • to chain jobs
    • callout to External web services
  • common scenarios:
    • performing sequential processing operations with external Web services

Batch Apex

  • run large jobs that would exceed normal processing limits
  • when to use:
    • for long-running jobs with large data volumes that need to be performed in batches, such as database maintenance jobs
    • for jobs that need larger query results than regular transactions allow
  • common scenarios:
    • data cleansing or archiving of records

Scheduled Apex

  • schedule Apex to run at a specified time
  • when to use:
    • to schedule an Apex class to run on a specific schedule
  • common scenarios:
    • daily or weekly tasks

Was it helpful? Check out our other great posts here.

Resources

5 12 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Tushar K
Tushar K
11 months ago

Great post!!!

Close Menu
1
0
Would love your thoughts, please comment.x
()
x