Thursday, December 12, 2024
7.2 C
London

How to Write a Batch Apex in Salesforce

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

Hot this week

How Do Local Development Companies Cater to Qatar’s Cultural and Business Environment?

Qatar’s unique cultural and business environment presents opportunities and...

Online Cricket ID: Instant Betting through Online Cricket ID

Online Cricket ID – Bet on All Formats of...

24-Hour Ambulance Services in Delhi at LifeExpress Healthcare

In a bustling metropolis like Delhi, access to reliable...

How Modular Office Furniture Helps You Achieve the Perfect Work-Life Balance

Achieving a healthy work-life balance has become one of...

Manage Customer Data: Top 5 Recommendations How to Manage Customer Data

In an ideal world, your company’s consumer data is...

Topics

How Do Local Development Companies Cater to Qatar’s Cultural and Business Environment?

Qatar’s unique cultural and business environment presents opportunities and...

Online Cricket ID: Instant Betting through Online Cricket ID

Online Cricket ID – Bet on All Formats of...

24-Hour Ambulance Services in Delhi at LifeExpress Healthcare

In a bustling metropolis like Delhi, access to reliable...

How Modular Office Furniture Helps You Achieve the Perfect Work-Life Balance

Achieving a healthy work-life balance has become one of...

Manage Customer Data: Top 5 Recommendations How to Manage Customer Data

In an ideal world, your company’s consumer data is...

Everything You Need to Know About the Sp5der Hoodie

The Sp5der hoodie has emerged as a distinguished call...

The Role of Technology in Glo Gang Apparel Design

Discover Glo Gang, the USA based clothing brand, offering unique, stylish, and high quality apparel that reflects bold streetwear culture Shop now

Digital Marketing Services: Driving Business Growth

In today’s fast-paced, technology-driven world, digital marketing has become...

Related Articles

Popular Categories