2014年3月26日水曜日

jqueryで動的に出力したhtmlでのイベントを受け取る

最近今更ながらjqueryをがりがり書いていて、
それで久々にはまったのでメモ。
こういうプルダウンがあって、選択した値をもとに何か処理を行いたいとき、
<select id="test1" name="select1">
 <option value="1">no1</option>
 <option value="2">no2</option>
 <option value="3">no3</option>
</select>
最初から出力されてるプルダウンだとこの書き方で実行されるけど、
$('select[name="select1"]').change(function(){
  alert($('#test1').val());
});

動的に出力したプルダウンだと実行されなくて、
この書き方にしないと実行されなかった。
$(document).on('change','select[name="select1"]',function(){
  alert($('#test3').val());
});
動的にhtml書き出しているからそうといえばそうだけど、 意外な盲点でした。
githubにもサンプルコードあげました。
https://github.com/syakasyaka/html/blob/master/jquery-dynamic-on.html

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は前回の処理が終了してからの時間で動くといった違いのようです。