Salesforce Batch Apex 批处理(四)Send Mail Example

2021-11-22 21:58:12 浏览数 (1)

在execute方法执行完成后,调用finish方法,一般用来发送邮件和后续处理,发送邮件具体写法如下

代码语言:javascript复制
global with sharing class ExampleOwnerReassignmentBatch implements Database.Batchable<sObject>,
                                                        Database.Stateful,
                                                        Database.AllowsCallouts {
    public final String query;
    public final String email;
    public final Id toUserId;
    public final Id fromUserId;
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, list<sObject> scope) {
        Savepoint sp = Database.setSavepoint();
        try {
            List<Opportunity> opps = new List<Opportunity>();
            for(sObject item : scope){
                Opportunity opp = (Opportunity)item;
                if(opp.OwnerId == fromUserId){
                    opp.OwnerId=toUserId;
                    opps.add(opp);
                }
            }
            update opps;
        } catch (Exception ex) {
            Database.rollback(sp);
        }
    }
    global void finish(Database.BatchableContext BC) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {email});
        mail.setReplyTo('xxx@qq.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

调用Batch类

代码语言:javascript复制
Id fromUser = [SELECT Id, Name FROM User WHERE Name = 'logon xiang'].Id;
Id toUser = [SELECT Id, Name FROM User WHERE Name = 'System'].Id;
ExampleOwnerReassignmentBatch reassign = new ExampleOwnerReassignmentBatch();
reassign.query = 'SELECT Id, Name, OwnerId, Owner.Name FROM Opportunity WHERE DeleteFlg__c = true';
reassign.email='xxxxxxxxxxxxx@163.com';
reassign.fromUserId = fromUser;
reassign.toUserId = toUser;
ID batchprocessid = Database.executeBatch(reassign);

Batch执行前,OpportunityObject的数据,

Batch执行后,Opportunity更新后如下

0 人点赞