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

☆樱花仙子☆ 提交于 2019-12-11 07:42:11

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/6038880/hot-to-run-a-class-method-in-spring-as-a-thread-when-the-app-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!