Question

I want to setup timer task through spring.xml and timer should start whenever applicationContext is loaded.

I am reading this tutorial from Spring: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

But I don't find any information about how spring will start timer start executing. For example, Using Timer class we can say: new Timer(new Task).schedule() and then it will right away start executing tasks, how will that work with following configuration?

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
  }
}

Spring Configuration:

<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>
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
        <list>
            <!-- see the example above -->
            <ref bean="scheduledTask" />
        </list>
    </property>
</bean>
Was it helpful?

Solution

org.springframework.scheduling.timer.TimerFactoryBean will set up timers after application context is initialized.

Use the source Luke: http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-context/2.5.3/org/springframework/scheduling/timer/TimerFactoryBean.java#TimerFactoryBean.afterPropertiesSet%28%29

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top