LoginSignup
17
14

More than 5 years have passed since last update.

Apexバッチ

Last updated at Posted at 2017-02-15

バッチクラス

バッチ用インターフェースを継承する

global class XxxBatch 
  implements Database.Batchable<sObject>, Database.Stateful {
//Database.Statefulを付けると、Batchクラスのインスタンス変数(またはプロパティ)の値がトランザクション内(start -> execute -> finish)で引き継がれるようになる
//付けない場合はインスタンス変数は呼出し毎に初期化されることに注意(クラス変数も同じ扱い)

//この形式の場合は Iterable start()メソッドの実装が必要となる。sObjectレコード以外でバッチ処理を使う場合はこちら
global class XxxBatch 
  implements Database.Batchable<XXX__c>, Database.Stateful {

所定のインターフェースを実装する

/*
 * バッチ処理開始時に最初に呼び出される
 * バッチ処理対象のレコードを返却するQueryLocatorを返す
 */ 
global Database.QueryLocator start(Database.BatchableContext bc) {
    String query = 'SELECT ** FROM XX';
    return Database.getQueryLocator(query);
}

/*
 * バッチ処理の終了時に呼び出される
 * 終了処理を実装する
 */
global void finish(Database.BatchableContext bc) {
    ....
}

/*
 * バッチサイズで指定されたレコード数単位で executeが呼び出される
 *  targetRecords: 対象となるレコード
 */
global void execute(Database.BatchableContext bc, List<sObject> targetRecords) {
    ....
}

execute()メソッドからExceptionが投げられるとトランザクションがロールバックされる。メールを投げる処理も内部的にはトランザクション管理されているので、結果的にメールが飛ばないことに注意(エラー時にメールを投げるような実装をする場合はtry-catchで例外を掴まえてExceptionを投げないようにする必要がある)

スケジューラクラス

スケジュールの設定は[設定] - [開発] - [Apexクラス] or コマンド実行で。

public class DailyBatchScheduler implements Schedulable {
    private final Integer BATCH_SIZE = 200;

    public void execute(SchedulableContext ctx) {
        DailyBatch b = new DailyBatch();
        Database.executeBatch(b, BATCH_SIZE);
    }
}

Apexからのバッチ実行

Xxx batch = new XxxBatch();
Database.executeBatch(batch, 500);  //バッチサイズは500レコード

物理的にレコードを削除

//データをハードデリートする方法
  delete scope;   
  Database.emptyRecycleBin(scope); 
17
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
14