How can I call this Batch Class from Lightning component?

 global class BatchSync implements Database.Batchable<sObject>,   Database.AllowsCallouts {

 public String query = 'Select ID, Name from Account';
 global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);

     global void execute(Database.BatchableContext BC, List<Account> records) {         
        String endpoint;        

        for ( integer i = 0; i< records.size(); i++ ){
         try {                  
          HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          // Set values to Params

          endpoint = 'Your endpoint';

          req.setHeader('Authorization', header);
          req.setHeader('Content-Type', 'application/json');
          req.setBody('Information you wanna send');
          req.setCompressed(true); // This is imp according to SF, but please check if
                                 // the webservice accepts the info. Mine did not :P
                                 // Had to set it to false

          if (!Test.isRunningTest()) {      
            res = http.send(req);
            String sJson = res.getBody();
            System.debug('Str:' + res.getBody());
          // now do what u want to with response.               
          catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );           

    global void finish(Database.BatchableContext BC){    

You cannot execute batch directly from Lightning component. For this, you need to use a @AuraEnabled method, from that method you can execute the batch.

public static Account getAccount(Id accountId) {
    // do some preprocessing.
    // execute the batch here
    Id jobId = Database.executeBatch(new BatchSync()); // optional batch size can be provides as well.

You can also monitor the batch status querying AsyncApexJob

Aura Enabled Methods

Batch Apex


  • 2
    Do we need (cacheable=true) ? My theory is cacheable is for retriveing data and it does not allow dml – Pranay Jaiswal Jul 2 '19 at 10:17
  • It seems to me you really don't want this cacheable - you want to ensure that each invocation of the method is actually made against the serve. – Phil W Jul 2 '19 at 10:33
  • Yes, we don't need it, It was added by mistake. Thanks for the correction – rahul gawale Jul 2 '19 at 10:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.