Can we call future method from batch class?

1.0K    Asked by AvaBlack in Salesforce , Asked on Mar 2, 2023

 I have a requirement where a future method needs to be called from batch apex.I came across various articles stating that a future method could not be called from the batch. Are there any alternate solutions for that?

Answered by Diya tomar

The answer to your question - can we call future method from batch class is - The general solution to this and other async problems (i.e. unlimited future calls) was proposed with code samples by Dan Appleman at Dreamforce 13. The code can be found at http://advancedapex.com/dreamforce13/ The essence of the solution is to use a custom object to store all async requests and then have a scheduled class launch a batch job to process each async request one-by-one, restarting the scheduled job in the finish() method if there are new async requests created since the batch was started.


Your Answer

Answer (1)

No, you cannot directly call a @future method from within a batch class in Salesforce.


@future methods are designed to run asynchronously and are typically used for executing long-running or potentially blocking operations outside the context of the current transaction. They are invoked by the platform's Future Method Executor and execute separately from the main transaction.

Batch classes, on the other hand, are used for processing large volumes of data in chunks, typically within the same transaction context. They are designed to be run synchronously within the context of the current transaction.

However, you can achieve a similar result by implementing the Database.AllowsCallouts interface in your batch class and making a callout to an external service that, in turn, invokes the desired asynchronous process. Here's a basic example:

global class MyBatchClass implements Database.Batchable, Database.AllowsCallouts {

    global Database.QueryLocator start(Database.BatchableContext bc) {
        // Query the records to be processed
        return Database.getQueryLocator([SELECT Id, Name FROM MyObject__c]);
    }
    global void execute(Database.BatchableContext bc, List scope) {
        // Perform any necessary processing
        // Make a callout to an external service that invokes the @future method
        MyFutureClass.makeAsyncCall();
    }
    global void finish(Database.BatchableContext bc) {
        // Perform any post-processing tasks
    }
}

In this example, MyFutureClass.makeAsyncCall() represents the callout to the external service, which then invokes the desired @future method. Note that making callouts from batch classes requires careful consideration of Salesforce's governor limits and best practices for handling callouts.

5 Months

Interviews

Parent Categories