Quartz和Spring:动态调度

时间:2015-06-11 11:01:16

标签: java spring quartz-scheduler

我有一项网络服务,可以对某项工作进行动态安排。该作业是一个Java类,它扩展了Quartz Job接口

public class StartJob implements Job {
    private String jobId;
    private DAO dao;

    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobDataMap dataMap = context.getMergedJobDataMap();

        //some logic here
    }

    // getters and setters
}

我还公开了一个API,它接收一个jobId一个cron表达式,并安排一个具有接收到的id的新StartJob。这是我的 Spring配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "persistence.dao" })
@ImportResource({"spring-quartz-context.xml"})
public class BeanConfig {
    //wired from the xml
    @Autowired JobDetailFactoryBean jobDetailFactory;
    @Autowired CronTriggerFactoryBean cronTriggerFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setApplicationContextSchedulerContextKey("applicationContext");
        bean.setSchedulerName("MyScheduler");
        Map<String, Object> schedulerContextAsMap = new HashMap<String, Object>();
        bean.setSchedulerContextAsMap(schedulerContextAsMap);
        // quartzproperties not reported
        bean.setQuartzProperties(quartzProperties());

        return bean;
    }

    //other bean definitions

}

和spring-quartz-config.xml

<bean name="complexJobDetail"
    class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="jobs.StartJob" />
    <property name="durability" value="true" />
</bean>

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="complexJobDetail" />
    <property name="cronExpression" value="0/5 * * ? * SAT-SUN" />
</bean>

我想做的事情就像(伪代码)

JobDetail job = jobDetailFactory.getObject();
job.setName(aGeneratedUUID);
CronTrigger trigger = cronTriggerFactory.getObject();
trigger.setCronExpression(aDynamicCronExpression);

scheduler.schedule(job, trigger);

但问题是我无法更改作业名称,因此,仅安排了第一份作业。第一个作业使用JobDetailFactoryBean的名称作为名称(complexJobDetail)。

我在这里缺少什么?这个配置是否正确?从工厂检索的作业和触发器是同一个类的新实例还是它们是同一个类实例?

1 个答案:

答案 0 :(得分:0)

问题在于我没有调用方法afterPropertiesSet()。所以

jobDetailFactory.setName(generatedUUID);
jobDetailFactory.afterPropertiesSet();
JobDetail job = jobDetailFactory.getObject();

有效,创建的作业有新名称。