在一些業務場景下,我們需要指定時間,定期執行某段代碼,比如定期清理垃圾,同步數據等。接下來以生日提醒爲例完成一個Demo。
創建一個對象Friend__c,裏面包含字段:日期字段生日birthday__c和公式字段生日提醒時間remainder__c<等於生日日期-3>。計劃任務的代碼如下:
global class BirthdayRemindBatchScheduler implements Schedulable{
global void execute(SchedulableContext SC){
Database.executeBatch(new BirthdayReminderBatch(),200);
}
}
計劃任務的實現類必須實現Schedulable接口,並覆蓋execute方法。
然後選擇依次選擇:開發→Apex類→計劃Apex。
設置作業名稱,選定要執行計劃任務類以及執行時間,保存。
這種方式只能將執行時間精確到小時,如果要更精確的時間需要使用代碼在後臺實現。
所有計劃執行的任務都可以在作業→計劃的作業中查看:
接下來是生日提醒的具體實現,BirthdayReminderBatch實現
global class BirthdayReminderBatch implements Database.Batchable<sObject> {
public Date todayy;
public String myEmailAddress = '[email protected]';//這裏的郵箱最好不寫QQ郵箱地址,某些情況下Salesforce平臺給QQ郵箱發送的郵件收不到
global BirthdayReminderBatch() {
todayy = Date.today();
System.debug('todayy:' + todayy);
}
global List<Friend__c> start(Database.BatchableContext BC) {
//remainder__c:生日提醒是作爲一個輔助字段存在,用公式來快速定位時間,避免在類中操作
List<Friend__c> list_con = new List<Friend__c>([select Id,Name,ownerId,owner.email from Friend__c where remainder__c =: todayy]);
System.debug('*****朋友的信息*****' + list_con);
return list_con;
}
global void execute(Database.BatchableContext BC, List<Friend__c> scope) {
System.debug('*****execute_contact*****' + scope);
//發送郵件
for(Friend__c fri : scope){
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[]{myEmailAddress});
email.setSubject('生日提醒');
email.setHtmlBody('您好,' + fri.Name + '的生日還有三天,請做好相關準備!');
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
}
}
global void finish(Database.BatchableContext BC) {
}
}
計劃任務大部分情況下是與批處理一起使用的,實現批處理的類需要實現Database.Batchable<sObject>接口,並覆蓋其三個生命週期方法:
//start方法,主要用於對數據的初始化和準備工作
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc){}
//execute 方法,主要對數據的處理,每次都會被執行,業務邏輯的核心方法
global void execute(Database.BatchableContext BC, list<P>){}
//finish方法,主要用於批處理結束後的後續處理,比如發送郵件等
global void finish(Database.BatchableContext BC){}
execute 中方法的List<P>集合即爲start方法的返回值,可以直接在方法中使用。
批處理方法可以在頁面上通過按鈕來調用,也可以在後臺通過代碼,或者計劃任務來調用。
在Apex中,對SQOL的操作有着諸多限制,譬如一次執行的SOQL的次數不能超過100次,查詢的數據不能超過5000條等,遇到因爲對於DML操作有限制,比如因爲項目需求,需要修改50萬條數據,直接調用Database.update()便會拋出異常,如果需要達到目的,就只能使用批處理。
以上,希望能幫助到需要的朋友。