Jul 29, 2024
22 Views
Comments Off on How to Write a Batch Apex in Salesforce
0 0

How to Write a Batch Apex in Salesforce

Written by

In this post, let us learn about the Batch Apex and its usage. Once after completing this post, you will be able to write a batch class very comfortably.

When to go for Batch Apex?

As a developer, we may come across situations to handle thousands of records for a database operation. In those cases, batch apex simplifies our processing time and system complexity. Batch apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks.

These jobs can be programmatically invoked at runtime using apex. We can have only 5 queued or active batch jobs at one time.

How to use Batch apex?

Write an apex class – by implementing the interface Database.Batchable and then invoke the class programmatically.

Database.Batchable – Contains 3 methods

Start()

return type: Iterable |Querylocatorarguments : Database.batchableContextexecute()

no return typearguments : Database.batchableContext , List<Sobject> scopefinish()

no return typearguments : Database.batchableContextExample: Use Case: Reassign Account owner

global class OwnerReassignment implements Database.Batchable<sObject> {
	String query;
	String email;
	Id toUserId;
	Id fromUserId;
	global Database.querylocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}
	global void execute(Database.BatchableContext BC, List<sObject> scope) {
		List<Account> accns = new List<Account>();
		for(sObject s : scope){Account a = (Account)s;
		if(a.OwnerId==fromUserId) {
			a.OwnerId=toUserId;accns.add(a);
		}
	}
	update accns;}global void finish(Database.BatchableContext BC) {
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.setToAddresses(new String[] {email});
		mail.setReplyTo('batch@acme.com');
		mail.setSenderDisplayName('Batch Processing');
		mail.setSubject('Batch Process Completed');
		mail.setPlainTextBody('Batch Process has completed');
		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
}

The above code can be run by executing the below snippet from Anonymous window

OwnerReassignment reassign = new OwnerReassignment();
reassign.query = 'SELECT Id, Name, Ownerid FROM Account ' + 'WHERE ownerid="' + u.id + '"'; 
reassign.email = 'admin@acme.com';
reassign.fromUserId = u;
reassign.toUserId = u2;
ID batchprocessid = Database.executeBatch(reassign);

References: Salesforce apex developer guide

Article Categories:
Coding and Scripting
Priya Singh
https://thestarbiznews.com/

Expertise: Technology Trends, Startups, Digital Disruption Bio: Priya Singh is a tech-savvy millennial with a finger on the pulse of the ever-evolving digital landscape. A graduate of Stanford's Computer Science program and a former engineer at a Silicon Valley giant, Priya has a deep understanding of the technologies shaping our future. Her passion lies in demystifying complex tech jargon and exploring the disruptive potential of emerging trends, making her articles essential reading for anyone who wants to stay ahead of the curve. When not scouring the web for the latest tech tidbits, Priya enjoys traveling to off-the-beaten-path destinations and immersing herself in diverse cultures, always seeking new inspiration and insights.