deafult batch size == 200
implements Database.Batchable<>
global class MyBatchClass implements Database.Batchable<sObject> { global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) { // collect the batches of records or objects to be passed to execute } global void execute(Database.BatchableContext bc, List<P> records){ // process each batch of records } global void finish(Database.BatchableContext bc){ // execute any post-processing operations } }
배치 할 instance Database.getQueryLocator(query)로 반환
global Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id, Name FROM Account'; return Database.getQueryLocator(query); }
List<>로 start() 반환 값 넘어옴
global void execute(Database.BatchableContext BC, List<Account> accList) { // process each batch of records default size is 200 for(Account acc : accList) { acc.Name = acc.Name + 'sfdcpoint'; } try { update accList; } catch(Exception e) { System.debug(e); } }
모든 배치가 처리된 후 한 번 호출
- 배치 작업 실행
: Database.executeBatch( )의 매개변수로 내가 만든 배치클래스 객체를 넘긴다.- Batch 작업 진행상황 추적
: AsyncApexJob Object에서 Database.executeBatch()로 반환된 batchId를 이용해서 진행 상황 추적
MyBatchClass myBatchObject = new MyBatchClass();
Id batchId = Database.executeBatch(myBatchObject);
Id batchId = Database.executeBatch(myBatchObject, 100); // batch size change
// Batch 작업 진행상황 추적
AsyncApexJob job = [
SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE ID = :batchId ];
implements Schedulable
global class scheduledBatchable implements Schedulable { global void execute(SchedulableContext sc) { BatchApexExample b = new BatchApexExample(); Database.executeBatch(b); } }
@isTest
private class BatchApexExampleTest {
static testmethod void test() {
// Create test accounts to be updated by batch
Account[] accList = new List();
for (Integer i=0;i<100;i++) {
Account ac = new Account(Name = 'Account ' + i);
accList.add(ac);
}
insert accList;
Test.startTest();
BatchApexExample b = new BatchApexExample();
Database.executeBatch(b);
// if use scheduling at batch class
String CRON_EXP = '0 0 9 * * ? *';
System.schedule('scheduledBatchable_test', CRON_EXP, new scheduledBatchable());
Test.stopTest();
// Verify accounts updated
Account[] accUpdatedList = [SELECT Id, Name FROM Account];
System.assert(accUpdatedList[0].Name.Contains('sfdcpoint'));
}
}