As we discussed in Future class, to overcome the control over the tracking of the future methods running status.
Queuable apex takes control of your asynchronous Apex processes by using the Queueable interface. This interface enables you to add jobs to the queue and monitor them.
To use Queueable Apex, a developer needs to create a class that implements the “Queueable” interface. The class must define a “execute” method that contains the code to be executed asynchronously. Once the class is created, it can be added to the queue using the “System.enqueueJob” method.
Each queued job runs when system resources become available. A benefit of using the Queueable interface methods is that some governor limits are higher than for synchronous Apex, such as heap size limits.
Variables that are declared transient are ignored by serialization and deserialization and the value is set to null in Queueable Apex.
Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record.
public class AsyncExecution implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name=’Sruvi’,Phone=’9701432826′);
insert a;
}
}
To add this class as a job on the queue, call this method:
ID jobID = System.enqueueJob(new AsyncExecutionExample());
This query will be helpful to query the Asynchronous jobs are running in the system.
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
we can add up to 50 jobs to the queue with System. enqueueJob in a single transaction.
Here are some interesting questions about Queuable apex :
Q: What is QueueableContext?
A: It is an interface that is implemented internally by Apex, and contains the job ID. Once you queue the Queueable Job, the Job Id will be returned to you, by apex through QueueableContext’s getJobId() method.
Q: Can I do callouts from a Queueable Job?
A: Yes, you have to implement the Database.AllowsCallouts interface to do callouts from Queueable Jobs.
Q: Can I chain a job that has implemented allowsCalloutsfrom a Job that doesn’t have?
A: Yes, callouts are also allowed in chained queueable jobs.
Q: Can I call Queueable from a batch?
A: Yes, But you’re limited to just one System.enqueueJob call per execute in the Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.
Q: If I have written more than one System.enqueueJob call, what will happen?
A: System will throw LimitException stating “Too many queueable jobs added to the queue: N”.
