2009. 10. 20. 20:20
[Spring] Using JDK Timer support / JDK 타이머 지원 기능 사용
2009. 10. 20. 20:20 in Java/Spring
원문: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch25s07.html
스프링에서 작업을 스케줄하는 다른 방법은 JDK Timer 객체를 사용하는 것입니다. 타이머를 생성하거나 메소드를 호출하는 타이머를 사용할 수 있습니다. TimerFactoryBean을 사용하여 타이머를 연동할 수 있습니다.
TimerTask를 사용하여 Quartz 작업과 유사한 타이머 태스크를 생성할 수 있습니다:
public class CheckEmailAddresses extends TimerTask { private List emailAddresses; public void setEmailAddresses(List emailAddresses) { this.emailAddresses = emailAddresses; } public void run() { // iterate over all email addresses and archive them } }
연동은 간단합니다:
<bean id="checkEmail" class="examples.CheckEmailAddress"> <property name="emailAddresses"> <list> <value>test@springframework.org</value> <value>foo@bar.com</value> <value>john@doe.net</value> </list> </property> </bean> <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <!-- wait 10 seconds before starting repeated execution --> <property name="delay" value="10000" /> <!-- run every 50 seconds --> <property name="period" value="50000" /> <property name="timerTask" ref="checkEmail" /> </bean>
참고: 단 한 번만 태스크를 실행하려면 period 속성을 0(또는 음수)로 변경해야 합니다.
Quartz 처럼, Timer 도 주기적으로 메소드를 호출하는 기능을 지원합니다:
<bean id="doIt" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> </bean>
Q위의 예제는 exampleBusinessObject의 doIt 메소드를 호출할 것입니다:
public class BusinessObject { // properties and collaborators public void doIt() { // do the actual work } }
Changing the timerTask
reference of the ScheduledTimerTask
example to the bean doIt
will result in the doIt
method being executed on a fixed schedule.
The TimerFactoryBean
is similar to the Quartz SchedulerFactoryBean
in that it serves the same purpose: setting up the actual scheduling. TheTimerFactoryBean
sets up an actual Timer
and schedules the tasks it has references to. You can specify whether or not daemon threads should be used.
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <!-- see the example above --> <ref bean="scheduledTask" /> </list> </property> </bean>