Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Code used in "How to create a Batch Class in Salesforce Apex? | Batch Apex | Apex Tutorial Series by SFDC Stop" (
* Author:- Rahul Malhotra
* Description:- This batch class is used to update all contacts who have opted out of email, call and fax
* Created:- 18-12-2021
* Last Updated:- 18-12-2021
public class UpdateContactsBatch implements Database.Batchable<sObject> {
// * Return a maximum of 50 million records
public Database.QueryLocator start(Database.BatchableContext batchableContext) {
return Database.getQueryLocator('SELECT Id FROM Contact WHERE Unsubscribe_Date__c < TODAY');
public void execute(Database.BatchableContext batchableContext, List<SObject> contacts) {
for(sObject contact : contacts) {
contact.put('DoNotCall', true);
contact.put('HasOptedOutOfEmail', true);
contact.put('HasOptedOutOfFax', true);
update contacts;
public void finish(Database.BatchableContext batchableContext) {
// * Execute a final operation once the batch is complete
// * Execute batch
Database.executeBatch(new UpdateContactsBatch());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment