Sunday, April 1, 2012

Spring Managed DI for Quartz Jobs With Dependencies

Problem Statement:

Quartz scheduler (v 2.1.3) triggers a job which has its own dependencies which needs to be managed using Spring (3.1.1.RELEASE+)

Solution:

The Job

public class HttpDealsDownloadJob implements Job {
// NO DEPENDENCIES HERE
  @Override
  public void execute(final JobExecutionContext context)
      throws JobExecutionException {
    final JobDataMap jdm = context.getJobDetail().getJobDataMap();
// EXTRACT YOUR DEPENDENCY FROM JOB DATA MAP
    final HttpFileDownloader delegate = (HttpFileDownloader) jdm
        .get("job.delegate");
    delegate.apply(context.getJobDetail().getJobDataMap().getWrappedMap());
  }

}

Spring Context

<bean id="mySchedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="configLocation" value="file:quartz.properties" />
<property name="jobFactory" ref="springBeanJobFactory" />
<property name="triggers">
<list>
<ref bean="myCronTriggerFactoryBean" />
</list>
</property>
</bean>
<bean id="springBeanJobFactory"
class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
<bean id="myCronTriggerFactoryBean"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="cronExpression" value="${my.cron.expression}" />
<property name="jobDetail" ref="myJobDetailFactoryBean" />
</bean>
<bean id="myJobDetailFactoryBean"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobDataAsMap">
<map>
<entry key="source.url" value="${my.deals.url}" />
<entry key="job.delegate" value-ref="httpFileDownloader" />
</map>
</property>
<property name="jobClass"
value="org.zero.gb.acequia.scheduler.HttpDealsDownloadJob" />
<!-- INJECT APPLICATION CONTEXT -->
<property name="applicationContextJobDataKey" value="appicationContext" />
</bean>
<!-- THIS IS THE CLASS WHICH ACTUALLY DOES THE WORK -->
<bean id="httpFileDownloader" class="org.zero.acequia.integration.http.HttpFileDownloader">
             <!-- your dependencies here -->
     </bean>

No comments: