[SpringBoot] コピペでできる3ステップお手軽バッチ処理

2016.08.04

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

SpringBootでバッチ処理をしてみようと思い、SpringBatchを調べたのですが、もっとお手軽な方法がありましたのでご紹介します。

環境

Spring Tool Suite 3.8.0

手順

1ステップ

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SpringBootPracticeApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootPracticeApplication.class, args);
	}
}

@EnableSchedulingを記述して定期実行を有効にします。

2ステップ

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class BatchProcessing {

	@Autowired
	BusinessLogic businessLogic;
	
	@Scheduled(initialDelay = 10000, fixedDelay = 10000)
	public void fixedRate(){
		businessLogic.execute();
	}
}

定期実行したいメソッドに@Scheduledを記述します。 initialDelayは起動後、何秒後にメソッドを実行するのかを指定、fixedDelayは前回の実行終了後、何秒後にメソッドを実行するかを指定します。
fixedRateと書けば前回の実行開始時点から何秒後に実行するかを指定することができます。

11行目にcronの時刻を指定することも可能です。

@Scheduled(cron = "0 0 * * * *", zone = "Asia/Tokyo")

このように書けば、毎日0時0分に実行されるバッチ処理を書くことが可能です。

3ステップ

import org.springframework.stereotype.Component;

@Component
public class BusinessLogic {

	public void execute(){
		System.out.println("running");
	}
}

実行させたい処理を書いたクラスに@Componentをつけて、使用するクラスでは@Autowiredでメンバーに注入して実行するだけです。

最後に

他にも設定ファイルに書いたスケジュールを実行する機能もあるようなので機会があれば試してみようと思います。

参考

http://qiita.com/rubytomato@github/items/4f0c64eb9a24eaceaa6e