Apex Future Methods Simplified
Apex future methods give you the ability to execute a piece of code in near future.
In more technical terms, it let you make an asynchronous transaction while running your code in a synchronous transaction.
Future methods must be static, void and can accept only primitive data types as parameters.
Future methods don’t start until resources are available. They may be sitting there in Salesforce waiting for their turn to execute.
Future methods do not run in the same order as it was called. In order to have this functionality, we have to use Queueable Apex. We will be covering Queueable Apex in the next part of Asynchronous Transactions 🙂
It can be that two future methods which may run concurrently, which could lead to record locking and a runtime error if they are updating the same record.
Let’s understand more about future methods with an example. Suppose you are creating a ticket booking application and once the ticket is booked you wanted to send a notification to the user on Whatsapp. You can send notifications from a separate asynchronous transaction preventing users to wait for the notification part to complete.
Let’s write the snippet for it.
public class WhatsAppService {
@future(callout = true)
public static void sendWhatsAppAsync(String toNum, String message){
// logic to send the whatsapp messages
}
}
In the above code block, In order to make a plain method as future, we have declared the method with the annotation @future.
In order to make a callout in the future method, we have used (callout = true).
You can invoke future methods like any other methods in the synchronous transaction.
public class TicketBookingService {
public static void ticketBooking(String toNum){
// Ticket Booking Logic Here
String message = 'Hey! Your ticket has been booked :)'
WhatsAppService.sendWhatsAppAsync(toNum, message);
}
}
Apex Future Methods Governor Limits Considerations :
There is a limit of 50 future calls per APEX invocation and an additional limit in the number of future calls in 24 hour period.
The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.
This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.
We can not call a future method from another future method.
Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂