quartz中取得ServletContext

注册一个listener

   <listener>
      <listener-class>com.krm.slsint.common.web.listener.StartupListener</listener-class>
   </listener>

在listener中给scheduler加入ServletContext

 1 public class StartupListener implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener
 2 {
 3     public void contextInitialized(ServletContextEvent event)
 4     {
 5         try{
 6             Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
 7             scheduler.getContext().put("ServletContextForScheduler", event.getServletContext());  
 8         catch (SchedulerException e){
 9                     e.printStackTrace();
10             }
11         }
12     }

从JobExecutionContext中读出ServletContext,可以取得中间件路径

 1 public class BatchMailSendJob extends QuartzJobBean {
 2     @Override
 3     protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
 4         try {
 5             ServletContext servletContext = (ServletContext) context.getScheduler()
 6                     .getContext().get("ServletContextForScheduler");
 7             String dir = servletContext.getRealPath(File.separator);
 8         } catch (FileNotFoundException e) {
 9             // TODO Auto-generated catch block
10             e.printStackTrace();
11         } catch (SchedulerException se) {
12             // TODO Auto-generated catch block
13             se.printStackTrace();
14         }
15     }
16 }

下面是quartz的配置xml

<beans>
    <bean name="mailJob"  class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass">
            <value>com.krm.slsint.mail.task.BatchMailSendJob</value>
        </property>
        <property name="jobDataAsMap">
            <map>
                <entry key="timeout">
                    <value>5</value>
                </entry>
            </map>
        </property>
    </bean>
    <bean id="mailCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="mailJob"/>
        </property>
        <property name="cronExpression">
             <value>0 0/10 9-23 * * ? </value>
        </property>
    </bean>
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref local="mailCronTrigger"/>
            </list>
        </property>
    </bean>
</beans>

 

你可能感兴趣的:(quartz中取得ServletContext)