Ernest
Ernest

Reputation: 962

Hot to run a class method in spring as a thread when the app loads?

i need to run a class from quartz-schedualer, and i need it to be running always and parallel form the main app. The class will always be cheking for new files in a folder to process. I though to include it as a listener in the web.xml, how ever this way the constructor does not run, only the calss is loaded. Any sugestions ?

Here what i added in the web.xml:

<listener>
        <listener-class>com.bamboo.common.util.QuartzSchedualer</listener-class>
</listener>

This is how i declared the class:

public class QuartzSchedualer {

     public void QuartzSchedualer (){
                try{

                    // Grab the Scheduler instance from the Factory

                    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();


                    // and start it off

                    scheduler.start();


                    scheduler.shutdown();

                }  catch (SchedulerException se) {
            se.printStackTrace();
        }
     }

}

Thank you in advance!

Upvotes: 1

Views: 997

Answers (1)

abalogh
abalogh

Reputation: 8281

You don't need to include it in web.xml, just load your appcontext in your web.xml as you already do probably, and deal with the scheduling within spring:

The job referring to your business object which has the method to be invoked:

<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <property name="targetObject" ref="exampleBusinessObject" />
  <property name="targetMethod" value="doIt" />
  <property name="concurrent" value="false" />
</bean>

The trigger that takes care of firing the method:

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail" ref="exampleJob" />
  <!-- run every morning at 6 AM -->
  <property name="cronExpression" value="0 0 6 * * ?" />
</bean>

The schedulerFactoryBean for wiring the trigger:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
    <list>
      <ref bean="cronTrigger" />
    </list>
  </property>
</bean>

See further in Spring documentation for 2.5, here for 3.0.

Upvotes: 2

Related Questions