gpt4 book ai didi

java - quartz 和 Spring : dynamic scheduling

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:32 25 4
gpt4 key购买 nike

我有一个网络服务,可以对某项作业进行动态调度。该作业是一个扩展了 Quartz Job 接口(interface)的 Java 类

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) 作为名称。

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

最佳答案

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

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

工作正常,创建的作业具有新名称。

关于java - quartz 和 Spring : dynamic scheduling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30778957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com