2014年2月21日金曜日

springのスケジューラのfixedDelayとfixedRateの違い

springのスケジューラをよく使うのですが、
昔はcronで時間を設定していたのですが、
それだと決まった時間にしか動かないので、
起動時にも動かしておきたいってのを満たすために
init用の記述を追加しないといけなくて嫌だなって思い、
最近はfixedRateを使うようにしています。

んで思ったのがfixedRateともう一種類あるfixedDelayってどう違うんだ?
ってことなので両方書いて試してみました。

applicationContext.xmlからimportしてるschedule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

 <task:annotation-driven scheduler="scheduler"/>
 
 <task:scheduler id="scheduler" pool-size="2"/>
</beans>

javaファイル
package com.syakasyaka.common.scheduler;

import java.util.Calendar;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class MessageDisplayService {

 @Scheduled(fixedDelay=10000)
 public void fixedDelay() throws InterruptedException{
  System.out.println("fixedDelay" + "_" + Calendar.getInstance().get(Calendar.SECOND));
  Thread.sleep(5000);
 }

 @Scheduled(fixedRate=10000)
 public void fixedRate() throws InterruptedException{
  System.out.println("fixedRate" + "_" + Calendar.getInstance().get(Calendar.SECOND));
  Thread.sleep(5000);
 }
}
実行すると以下のように出力されました。
fixedRate_50
fixedDelay_50
fixedRate_0
fixedDelay_5
fixedRate_10
fixedRate_20
fixedDelay_20
fixedRate_30
fixedDelay_35
fixedRate_40
fixedRate_50

fixedRateは前回の処理が開始してからの時間で動いて、
fixedDelayは前回の処理が終了してからの時間で動くといった違いのようです。

2014年2月20日木曜日

ブログ始めました

アメブロとはてなブログで書いてたのですけど、
bloggerでブログ始めました。
Googleアドセンスやりたかったのでw