Use Case:
Write a class and schedule it:
- The class should send email to Users having “System Administrator” profile about the Closed (Won and Lost) Opportunities for the current month.
- 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 monthList<Opportunity> listOfClosedOps = [Select Id, Name, StageNameFrom OpportunityWhere CloseDate = THIS_MONTH and (StageName='Closed Won' or StageName='Closed Lost')];// Get user ids in a listProfile 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 StringString 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 valuesMessaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();email.setToAddresses(listOfUserIds);email.setSubject('Opportunities closed this month');email.setPlainTextBody(closedOpportunities);// Send emailMessaging.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.
@isTestprivate class EmailNotificationSchedulerTest {@testSetupstatic 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;}@isTeststatic void testEmailNotificationScheduler() {// Schedule the job inside the start and stop test methodsTest.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%