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
global class CloseInventoryTaskBatch implements Schedulable, Database.Batchable<sObject> {
 
    public static List<String> statusList = new List<String>{
            '01 分配', '02 接受', '05 延期'
    };
 
    global void execute(SchedulableContext sc) {
        Database.executeBatch(new CloseInventoryTaskBatch());
    }
 
    global CloseInventoryTaskBatch() {
    }
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
                SELECT Id, taskStatus__c, Finish_Date__c, delayToDate__c 
                FROM task__c 
                WHERE taskStatus__c IN: statusList 
                AND (RecordType.Name = '盘点检查计划' OR RecordType.Name = '温湿度检查计划')]);
    }
 
    global void execute(Database.BatchableContext BC, list<task__c> scope) {
        Date today = Date.today();
        Integer numberOfDays = Date.daysInMonth(today.year(), today.month());
        Date lastDayOfMonth = Date.newInstance(today.year(), today.month(), numberOfDays);
        // 每个月的最后一天才执行
        if(!Test.isRunningTest()){
            if (today != lastDayOfMonth) {
                return;
            }
        }
        
        List<task__c> tempList = new List<task__c>();
        for (task__c t : scope) {
            if (t.taskStatus__c == '05 延期' && t.delayToDate__c < = today) {
                t.taskStatus__c = '06 关闭';
                tempList.add(t);
            } else if ((t.taskStatus__c == '01 分配' || t.taskStatus__c == '02 接受') && t.Finish_Date__c < = today) {
                t.taskStatus__c = '06 关闭';
                tempList.add(t);
            }
        }
 
        if (!tempList.isEmpty()) {
            update tempList;
        }
    }
 
    global void finish(Database.BatchableContext BC) {
    }
}