How to show status of batch job in Visualforce page?

How to show status of batch job in Visualforce page?

Sample Batch:

global class AccountUpdate Implements Database.Batchable <sObject> {
    global Database.queryLocator start(Database.BatchableContext bc) {
        String SOQL = ‘SELECT Id, Description FROM Account’;
        return Database.getQueryLocator(SOQL);
    }


    global void execute(Database.BatchableContext bc, List<Account> listAccount) {
        for(Account a : listAccount) {
            a.Description = ‘Updated on ‘ + system.today();
        }
        update listAccount;
    }


    global void finish(Database.BatchableContext bc) {
    }
}


Visualforce Page:

<apex:page controller=”Sample”>
<apex:form >
    <apex:pageBlock id=”pg”>
        <apex:pageBlockSection rendered=”{!batchStatusBool}”>
            <apex:actionStatus id=”act” startText=”Checking…” />
            Batch Account Status is {!batchStatus}
            <apex:actionPoller interval=”5″ action=”{!checkBatchStatus}” enabled=”{!pollerBool}” reRender=”pg” status=”act”/>
        </apex:pageBlockSection>
        <apex:pageBlockButtons location=”bottom”>
            <apex:commandButton value=”Call Account Update Batch” action=”{!callAcctUpdateBatch}”/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Class:

public class Sample {
    public Boolean batchStatusBool {get;set;}
    public String batchStatus {get;set;}
    Id batchId;
    public Boolean pollerBool {get;set;}


    public Sample() {
        batchStatusBool = false;
        pollerBool = false;
    }
   
    public void callAcctUpdateBatch() {
        batchStatusBool = true;
        AccountUpdate obj = new AccountUpdate();
        batchId = Database.executeBatch(obj, 2);
        checkBatchStatus();
    }
   
    public void checkBatchStatus() {
        AsyncApexJob job = [SELECT Id, Status FROM AsyncApexJob WHERE Id =: batchId];
        batchStatus = job.Status;
        if(batchStatus == ‘Completed’) {
            pollerBool = false;
        } else {
            pollerBool = true;
        }
    }
}

Output:

Cheers!!!

Leave a Reply