Batch Apex Example

Here I am providing simple example to understnd how to run batch apex programatically. Below is the simple apex class which implements Database.Batchable interface.

global class batchAccountUpdate implements Database.Batchable<sObject> {
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		String query = 'SELECT Id,Name FROM Account';		
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext BC, List<Account> scope) {
		for(Account a : scope) {
			a.Name = a.Name + '******';
		}
		update scope;
	}
	
	global void finish(Database.BatchableContext BC) {
	}
}

Now, I want to run this batch apex class. To run the apex job, you have to call “database.executeBatch” method. open developer console and execute below line of code.

batchAccountUpdate bc = new batchAccountUpdate();
database.executeBatch(bc);

After executing the above code, the related job will run. To see/monitor Batch apex jobs go to Setup->jobs->Apex Jobs. Here you will see the status of Batch apex jobs like submitted date, Job Type, Status, Total Batches, Bathes processed, failures, submitted by, Completion date, Apex Class & Apex Job ID. And also you can abort the jobs which are in processing.

If you want to run apex job after, click on the button on the Visualforce page, then create a page and implement above login in controller & call that method after clicking on button in a Visualforce page.