top of page
Search

Monthly Delete Multiple Closed Won Opportunities

  • abhyash
  • Nov 2, 2022
  • 2 min read

Updated: Nov 5, 2022

V1 Prepared By: Abhyash Timsina – 2 November 2022


Motivation: Showcasing a demo where you need to monthly delete large amounts of obsolete closed won opportunities that were closed 30 days ago, and you want to do it with no human intervention and without a flow! Both a batch apex and a scheduled apex is required. Reason why we need a batch class? If you have to do a delete operation on more than 150 at a time, your schedule may fail because of 'Too Many DML Statements' error. Normally we would separate them into 2 apex classes but for this example we use a single apex class that does both. Note - This is a personal project and not intended for financial gain.


My Technical Components




Source Code for DeleteMultipleClosedWonOpportunities Apex Class (with annotation starting with //)


/**
 * Created by Abhyash Timsina on 2/11/2022.
 */

// Implements both Batch Apex and Schedulable Apex

global class DeleteMultipleClosedWonOpportunities implements Database.Batchable<SObject>, Schedulable {

    global DeleteMultipleClosedWonOpportunities() {
    }

// Specify your SOQL query here - we are looking for Opportunities where the formula field Mark For Deletion is true

    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('Select Id from Opportunity where Mark_For_Deletion__c = true');
    }

// This execute method is the batch action that happens to the SOQL query

    global void execute(Database.BatchableContext BC, List<Opportunity> opportunityScope) {
        delete opportunityScope;
    }

// Finish means what you want to happen once the execute operation is done. For example - you could send an email to a user informing how many opportunities were deleted

    global void finish(Database.BatchableContext BC) {
    }

// This execute method is for the scheduled class, which is calling the batch class

    global void execute(SchedulableContext SC) {
        Database.executeBatch(new DeleteMultipleClosedWonOpportunities());
    }

}

To Schedule Apex (run this from DEV console):


System.schedule('Delete Multiple Closed Won Opportunities', '0 0 12 1 1/1 ?', new scheduledCron ());

To check status of your scheduled job, go here:

{Your Salesforce Org}/lightning/setup/ScheduledJobs/home


To Generate other CRON expressions, I recommend this one:



Package Link:


If you need help in installing and getting this working – please contact me on LinkedIn

 
 
 

Comments


bottom of page