2

I have a vf page on which there is only one command button which on click calls "ExecuteBatch" method.

Method as given below :

 public void executeBatch() {
       ACPBoxInvoiceDataBatch batch = new ACPBoxInvoiceDataBatch ();
       Database.executeBatch(batch);
    }

Now I need to check the status of batch job and depending on success and failure, I need to show the message on VF page.

5

http://www.tehnrd.com/batch-apex-status-bar/

This is a nice Batch Status bar you might want to look into


And that i achecvied by check the AsyncApexJob.Status using the JobId from the Database.BatchableContext.

E.g.

    global void finish(Database.batchablecontext bc) {

    // Check batch status - IF COMPLETED then 
    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email, ExtendedStatus
        from AsyncApexJob where Id = :bc.getJobId()];        

    if(a.Status == 'Completed') {


        // 1. Send Email (CSV created in execute method)


        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        // Send the email to the job submitter
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('x70RecordExtract  Status: ' + a.Status);
            mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
            ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);

        // Add your attachment to the email.

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


        // 2. database.executebatch(new chain_batch(),200);

    }
} 
  • 1
    isnt there any method to directly check the status of batch?? – Ankita Singh Jul 17 '15 at 10:29
  • 1
    ya we can check – Arjun Khatri Jul 17 '15 at 10:39
  • In fact 1 month before only i had a requirement which says: need to email and run another batch in the 'Finish' method of batch ONLY IF the batch ran successfully. I would like to have batch status in the finish method (like the batch status as we see in the apex jobs), so that can check for it and if it was completed then finish() should perform necessary tasks. So for this i had return a batch will give you example – Arjun Khatri Jul 17 '15 at 10:41
  • could you please share the exapmle?? – Ankita Singh Jul 17 '15 at 10:43
  • ya sure will post that !!! – Arjun Khatri Jul 17 '15 at 10:44
2

Your page has to continuously poll the controller at a fixed time interval and display message on the basis of percent complete.

Sample Controller

    public class BatchRunController {
        public boolean batchProcessed;
        public BatchRunController(){
            batchProcessed = false;    
        }
        public String getMessage(){
            if(batchProcessed){
                Double itemsProcessed;
                Double totalItems ;
                for(AsyncApexJob a : [select TotalJobItems, Status, NumberOfErrors, MethodName, JobType, JobItemsProcessed, Id, 
CreatedDate, CreatedById, CompletedDate, ApexClassId, ApexClass.Name From AsyncApexJob where ApexClass.Name = 'ACPBoxInvoiceDataBatch' order by CreatedDate desc limit 1]){
                    itemsProcessed = a.JobItemsProcessed;
                    totalItems = a.TotalJobItems;
                }
                //Determine the percent complete based on the number of batches complete and set message
                if(totalItems == 0){
                    //A little check here as we don't want to divide by 0.
                    return 'Batch Job 0% Complete';
                }else{
                    return 'Batch Job ' + String.valueof(((itemsProcessed  / totalItems) * 100.0).intValue())+'% Complete.';
                }

            } else {
                return 'Batch Job not yet executed !!';
            }
        }

        public PageReference process() {
            ACPBoxInvoiceDataBatch batch = new ACPBoxInvoiceDataBatch();
            Database.executeBatch(batch);
            batchProcessed = true;
            return null;
        }

    }

Sample VF page

<apex:page controller="BatchRunController">
  <apex:form >
  <apex:pageBlock >
  <apex:actionPoller rerender="msg" interval="5"/>
    <apex:commandButton action="{!process}" value="EXECUTE" rerender="msg"/>
    <Br/><Br/>
  <apex:outputLabel value="{!Message}" id="msg" style="text-wight:bold;"/>
  </apex:pageBlock>
  </apex:form>
</apex:page>

Initial Display

enter image description here

Display after clicking Execute

enter image description here

After this display, the VF page keeps on polling and displaying appropriate percentages every 5 seconds, and it shows 100% after execution is complete. [Note - Polling will still continue]

  • 1
    i tried this..but nothing happens :( – Ankita Singh Jul 17 '15 at 11:09
  • 1
    Can you check debugs if it is polling ? – Amit Bangad Jul 17 '15 at 11:17
  • the problem is whenever i load a pageit says that the status is 100% even before clicking the button – Ankita Singh Jul 17 '15 at 11:25
  • Ok, i ll give a try and let you know. – Amit Bangad Jul 17 '15 at 12:22
  • Updated the answer - Checkout the POC – Amit Bangad Jul 17 '15 at 14:03
1

You need to query on crontrigger object to get details of submitted jobs as

List<CronTrigger> listCronTrigger  = [SELECT Id, OwnerId, CronExpression 
      FROM CronTrigger WHERE CronExpression like '% MyJobName'];
  system.debug(listCronTrigger);
  • but i need to check the status in my code and depending on that i need to display the message in vf page – Ankita Singh Jul 17 '15 at 10:20
-1

Below query can be used to get the Status of the Batch Job based on name

SELECT >APEX_CLASS_NAME<, MethodName,JobItemsProcessed,TotalJobItems, JobType, Status, NumberOfErrors, createdby.name, createddate 
FROM AsyncApexJob 
WHERE jobtype='BatchApex' AND apexclass.name=>BATCH_JOB_NAME<

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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