考慮一種情況,您希望每天處理大量的記錄,可能是清理數(shù)據(jù)或可能刪除一些未使用的數(shù)據(jù)。
Batch Apex是異步執(zhí)行的Apex代碼,專門用于處理大量記錄,并且在調(diào)節(jié)器限制方面比同步代碼具有更大的靈活性。
當(dāng)我們使用Batch Apex時(shí),我們必須實(shí)現(xiàn)Salesforce提供的接口Database.Batchable,然后以編程方式調(diào)用類。
您可以通過(guò)以下步驟監(jiān)視類:
要監(jiān)視或停止批處理Apex Batch作業(yè)的執(zhí)行,請(qǐng)轉(zhuǎn)到設(shè)置 - >監(jiān)視 - > Apex作業(yè)或作業(yè) - > Apex作業(yè)。
Database.Batchable接口有三個(gè)方法,我們必須實(shí)現(xiàn)如下:
Start開(kāi)始
讓我們看看他們中的每一個(gè)。
語(yǔ)法:
global (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {}
此方法將在啟動(dòng)批處理作業(yè)時(shí)調(diào)用,并收集將在其上操作批處理作業(yè)的數(shù)據(jù)。
請(qǐng)注意以下幾點(diǎn):
語(yǔ)法:
global void execute(Database.BatchableContext BC, list<sobject>){}其中,list <sObject <由Database.QueryLocator方法返回。
此方法在啟動(dòng)方法之后調(diào)用,并執(zhí)行批處理作業(yè)所需的所有處理。
語(yǔ)法:
global void finish(Database.BatchableContext BC){}
此方法在結(jié)束時(shí)調(diào)用,您可以執(zhí)行一些整理活動(dòng),例如發(fā)送包含有關(guān)處理的批處理作業(yè)記錄和狀態(tài)的信息的電子郵件。
讓我們舉一個(gè)例子,我們現(xiàn)有的化學(xué)公司,讓我們假設(shè)我們需要更新客戶狀態(tài)和客戶記錄的客戶記錄已被標(biāo)記為活動(dòng),并創(chuàng)建日期為今天。 這應(yīng)該每天進(jìn)行,并且應(yīng)該向用戶發(fā)送有關(guān)批處理狀態(tài)的電子郵件。 將客戶狀態(tài)更新為“已處理”,將客戶狀態(tài)更新為“通過(guò)批處理作業(yè)更新”。
//Batch Job for Processing the Records global class CustomerProessingBatch implements Database.Batchable{ global String [] email = new String[] {'test@test.com'};//Add here your email address here
//Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Statusc, APEX_Customer_Decscriptionc From APEX_Customerc WHERE createdDate = today AND APEX_Activec = true');//Query which will be determine the scope of Records fetching the same }
//Execute method global void execute (Database.BatchableContext BC, List scope) { List customerList = new List(); List updtaedCustomerList = new List();//List to hold updated customer for (sObject objScope: scope) { APEX_Customerc newObjScope = (APEX_Customerc)objScope ;//type casting from generic sOject to APEX_Customerc newObjScope.APEX_Customer_Decscriptionc = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; updtaedCustomerList.add(newObjScope);//Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {//Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size '+updtaedCustomerList.size());//Update the Records } }
//Finish Method global void finish(Database.BatchableContext BC){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
//Below code will fetch the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id System.debug('$$$ Jobid is'+BC.getJobId());
//below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('test@test.com');//Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed '+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); }}
要執(zhí)行此代碼,首先保存它,然后將以下代碼粘貼到execute anonymous中。 這將創(chuàng)建類的對(duì)象,而Database.execute方法將執(zhí)行批處理作業(yè)。 一旦作業(yè)完成,將在指定的電子郵件地址發(fā)送電子郵件。 確保您有一個(gè)客戶記錄已選中“活動(dòng)”。
//Paste in Developer Console CustomerProessingBatch objClass = new CustomerProessingBatch(); Database.executeBatch (objClass);
執(zhí)行此類后,請(qǐng)檢查您提供的電子郵件地址,您將收到包含信息的電子郵件。 此外,您可以通過(guò)監(jiān)視頁(yè)面和上面提供的步驟檢查批處理作業(yè)的狀態(tài)。
如果你檢查調(diào)試日志,那么你可以找到列表大小,它指示已處理了多少記錄。
我們一次只能有5個(gè)批處理作業(yè)。 這是Batch Apex的限制之一。
您可以通過(guò)Apex詳細(xì)信息頁(yè)面安排Apex類,以及如下:
第1步:轉(zhuǎn)到Setup => Apex類,單擊Apex類。
第2步:點(diǎn)擊Schedule Apex按鈕:
第3步:提供詳細(xì)信息:
第4步:然后點(diǎn)擊保存按鈕,您的類將被安排。
//Batch Job for Processing the Records global class CustomerProessingBatch implements Database.Batchable{ global String [] email = new String[] {'test@test.com'};//Add here your email address here//Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Statusc, APEX_Customer_Decscriptionc From APEX_Customerc WHERE createdDate = today AND APEX_Activec = true');//Query which will be determine the scope of Records fetching the same }
//Execute method global void execute (Database.BatchableContext BC, List scope) { List customerList = new List(); List updtaedCustomerList = new List();//List to hold updated customer for (sObject objScope: scope) { APEX_Customerc newObjScope = (APEX_Customerc)objScope ;//type casting from generic sOject to APEX_Customerc newObjScope.APEX_Customer_Decscriptionc = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Statusc = 'Processed'; updtaedCustomerList.add(newObjScope);//Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } </apex_customerc>
if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {//Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size '+updtaedCustomerList.size());//Update the Records }
}
//Finish Method global void finish(Database.BatchableContext BC){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
//Below code will fetch the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id System.debug('$$$ Jobid is'+BC.getJobId());
//below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('test@test.com');//Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed '+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed);
Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
}
//Scheduler Method to scedule the class global void execute(SchedulableContext sc) { CustomerProessingBatch conInstance = new CustomerProessingBatch(); database.executebatch(conInstance,100); }}
//Paste in Developer ConsoleCustomerProessingBatch objClass = new CustomerProessingBatch();Database.executeBatch (objClass);
更多建議: