高章伟
2023-03-03 d8dc84a3d56df839895f1c417a4d9cbee763d262
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * Class名: AgencyShareUpdateBatch
 * 理由: 现在只有 Agency_Opportunity__c, 以后会有扩展的可能
 */
//20230203 lt 计划的作业优化   ---  继承加“, Database.Stateful”,不然removeOtherSc方法空指针
global class AgencyShareUpdateBatch implements Database.Batchable<sObject>, Database.Stateful {
 
    //20230203 lt 计划的作业优化  一小时两次 start
    private BatchEmailUtil.ScBean scB1;
    //20230203 lt 计划的作业优化  一小时两次 end
 
    global AgencyShareUpdateBatch() {
    }
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
 
        //20230203 lt 计划的作业优化  一小时两次 start
        scB1 = BatchEmailUtil.setSc1('AgencyShareUpdateBatchSchedule', 0, 23, 0, '0 30 *', null);
        if (System.Test.isRunningTest() == false) {
            for(CronTrigger ct : [SELECT Id FROM CronTrigger WHERE CronJobDetail.Name =: scB1.scName]) {
                System.abortJob(ct.Id);
            }
            system.schedule(scB1.scName, scB1.scTime, new AgencyShareUpdateBatchSchedule());
        }
        //20230203 lt 计划的作业优化  一小时两次 end
 
        return Database.getQueryLocator([SELECT Id
                , OCSM_Owner__c
                , Department_Class_Opp__c
                , Department_Class_Opp__r.OwnerId
             FROM Agency_Opportunity__c
            WHERE NeedShareBatch__c = true
        ]);
    }
 
    global void execute(Database.BatchableContext bc, List<Agency_Opportunity__c> scope) {
        List<Agency_Opportunity__c> updList = new List<Agency_Opportunity__c>();
        for (Agency_Opportunity__c nObj : scope) {
            if (nObj.Department_Class_Opp__c != null
                    && nObj.OCSM_Owner__c != nObj.Department_Class_Opp__r.OwnerId) {
                nObj.OCSM_Owner__c = nObj.Department_Class_Opp__r.OwnerId;
            }
            updList.add(nObj);
        }
        update updList;
    }
 
    global void finish(Database.BatchableContext bc) {
        BatchEmailUtil.removeOtherSc('AgencyShareUpdateBatchSchedule', scB1.scName);  //20230203 lt 计划的作业优化 
 
        // 如果前一个603的batch正在等待状态,则取消掉前一个batch的执行
        List<AsyncApexJob> lstJobs = [SELECT Id FROM AsyncApexJob WHERE (Status = 'Queued' OR Status = 'Holding') AND ApexClass.Name = 'NFM603Batch'];
        for (AsyncApexJob job : lstJobs) {
            try {
                System.abortJob(job.Id);
            } catch(Exception ex ) {
                System.debug(ex);
            }
        }
        Id execBTId = Database.executebatch(new NFM603Batch(),1);
    }
}