Use Case:

Write a class and schedule it:

  1. The class should send email to Users having “System Administrator” profile about the Closed (Won and Lost) Opportunities for the current month.
  2. Schedule the class to execute on last weekday of the month 6 PM.
// Send email to users having System Administrator profile about the closed opportunities.
public class EmailNotificationScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
// Get list of opportunities which were closed won/lost in the month
List<Opportunity> listOfClosedOps = [Select Id, Name, StageName
From Opportunity
Where CloseDate = THIS_MONTH and (StageName='Closed Won' or StageName='Closed Lost')];
// Get user ids in a list
Profile adminProfile = [Select Id From Profile Where Name = 'System Administrator'];
List<Id> listOfUserIds = new List<Id>();
for(User usr : [Select Id From User Where ProfileId = :adminProfile.Id]) {
listOfUserIds.add(usr.Id);
}
// Get all the opportunities Name and StageName in a String
String closedOpportunities = 'Opportunity Name' + ' : ' + 'Status';
for(Opportunity op : listOfClosedOps) {
closedOpportunities = ClosedOpportunities + '\n' + op.Name + ' : ' + op.StageName;
}
sendmail(listOfUserIds, closedOpportunities);
}
public void sendmail(List<Id> listOfUserIds, String closedOpportunities) {
// Creating instance of email and set values
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(listOfUserIds);
email.setSubject('Opportunities closed this month');
email.setPlainTextBody(closedOpportunities);
// Send email
Messaging.sendEmail(new List<Messaging.SingleEmailMessage> {email});
}
}

/**
Run the below code in Execute Anonymous Window
*/
String cronExp = '0 0 18 LW * ?';
System.schedule('Closed Opportunities for the Month', cronExp, new EmailNotificationScheduler());

Test Class:

Test method to verify that job is scheduled and email is sent to the Admin Users.

@isTest
private class EmailNotificationSchedulerTest {
    @testSetup
static void dataSetup() {
Opportunity op1 = new Opportunity(Name = 'ClosedWonOpportunity', StageName = 'Closed Won', CloseDate = System.today());
insert op1;
Opportunity op2 = new Opportunity(Name = 'ClosedLostOpportunity', StageName = 'Closed Lost', CloseDate = System.today());
insert op2;
}
@isTest
static void testEmailNotificationScheduler() {
// Schedule the job inside the start and stop test methods
Test.startTest();
    String cronExp = '0 0 18 LW * ?';
    String jobId = System.schedule('Closed Opportunities for the Month',
cronExp,
new EmailNotificationScheduler());
Test.stopTest();
System.assertEquals(false, String.isBlank(jobId), 'JobId should not be empty');
}
}
Code Coverage: 100%
Like it ? Share : Do Nothing

Leave a Reply