以编程方式执行Spring Quartz触发工作

时间:2018-02-23 02:25:39

标签: java spring spring-boot quartz-scheduler javabeans

我有Sprint Boot - Java 8应用程序,它具有我在启动时配置的石英作业并设置计划。正如您对石英作业所期望的那样,作业按照计划自动运行。但是,现在我希望能够允许用户通过单击前端上的按钮来手动触发这些作业没有搞乱了该作业的正常调度。这是我的所有相关文件。

application.yml

quartz:
    fooCron: 0 0 1 * * ?
    fooGroup: foo-quartz-group

QuartzConfig.java

@Configuration
@ConfigurationProperties(prefix = "quartz")
public class QuartzConfig {
    private String fooCron;
    private String fooGroup;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private DataSource dataSource;

    @Bean
    public SchedulerFactoryBean quartzScheduler() {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);

        Trigger[] triggers = {fooTrigger().getObject()};

        SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
        quartzScheduler.setJobFactory(jobFactory);
        quartzScheduler.setTransactionManager(transactionManager);
        quartzScheduler.setDataSource(dataSource);
        quartzScheduler.setOverwriteExistingJobs(true);
        quartzScheduler.setSchedulerName("foo-scheduler");
        quartzScheduler.setQuartzProperties(quartzProperties());
        quartzScheduler.setTriggers(triggers);

        return quartzScheduler;
    }

    @Bean
    public CronTriggerFactoryBean fooTrigger() {
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(fooJob().getObject());
        cronTriggerFactoryBean.setCronExpression(fooCron);
        cronTriggerFactoryBean.setGroup(fooGroup);
        return cronTriggerFactoryBean;
    }

    @Bean
    public JobDetailFactoryBean fooJob() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        jobDetailFactoryBean.setJobClass(FooJob.class);
        jobDetailFactoryBean.setGroup(fooGroup);
        jobDetailFactoryBean.setDurability(true);
        return jobDetailFactoryBean;
    }

    @Bean
    public Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz/quartz.properties"));
        Properties properties = null;
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
        }

        return properties;
    }

    //setters
}

FooJob.java

@Service
public class FooJob implements Job {
    private final FooRepository fooRepo; //This is a repository class annotated with @Repository.

    public FooJob(FooRepository fooRepo) {
        this.fooRepo = fooRepo;
    }

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        //do stuff
    }
}

现在这在定时计划中运行起来很有趣。根据yml文件0 0 1 * * ?中的cron配置,作业每天凌晨1点执行。大!但是现在我想手动执行它。所以我构建了一个控制器来接收来自UI的手动触发请求。

QuartzController.java

@RestController
@RequestMapping("/quartz")
public class QuartzController {
    private SchedulerFactoryBean schedulerFactoryBean;
    private Scheduler scheduler;

    public DevopsController(final SchedulerFactoryBean quartzScheduler) {
        this.schedulerFactoryBean = quartzScheduler;
        scheduler = schedulerFactoryBean.getScheduler();
    }

    @PostMapping("/execute")
    public ResponseEntity executeJob() {
        HttpStatus status = OK;
        try {
            TriggerKey triggerKey = new TriggerKey("fooTrigger", "foo-quartz-group");
            Trigger trigger = scheduler.getTrigger(triggerKey);
            ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0);
            JobDetail jobDetail = scheduler.getJobDetail(trigger.getJobKey());
            Trigger newTrigger = TriggerBuilder.newTrigger()
                                               .forJob(jobDetail)
                                               .startNow()
                                               .withIdentity(triggerKey)
                                               .withSchedule(scheduleBuilder)
                                               .startAt(Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()))
                                               .build();
            //I have tried all 3 of the following lines
            scheduler.scheduleJob(jobDetail, new HashSet<>(Arrays.asList(trigger)), true);
            //scheduler.addJob(jobDetail, true);
            //scheduler.rescheduleJob(triggerKey, newTrigger);
        } catch (SchedulerException e) {
            status = BAD_REQUEST;
        }

        return new ResponseEntity<>(status);
    }
}

但每次我运行应用程序并点击控制器的scheduleJob方法时,我在控制台中都会出现以下错误:

org.quartz.SchedulerException: Job instantiation failed
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45)
    at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
    at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:375)
Caused by: java.lang.InstantiationException: com.test.jobs.FooJob
    at java.lang.Class.newInstance(Class.java:427)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance(AdaptableJobFactory.java:58)
    at org.springframework.scheduling.quartz.SpringBeanJobFactory.createJobInstance(SpringBeanJobFactory.java:74)
    at com.test.config.AutowiringSpringBeanJobFactory.createJobInstance(AutowiringSpringBeanJobFactory.java:27)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41)
    ... 2 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.test.jobs.FooJob.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)
    ... 6 common frames omitted

我究竟做错了什么?如何让这个作业按计划自动运行,但也可以根据手动请求执行?

我正在使用sprint boot 1.5.9.RELEASE和quartz 2.2.1

1 个答案:

答案 0 :(得分:1)

@scary-wombat所述,您必须在<input type="hidden" name="Index" value = "@i" />中添加无参数构造函数。您的方法存在的问题是您不会以这种方式获得FooJob

FooRepository

您有2个选项

1)如果public FooJob() { } 有@Respository注释,您可以将@Autowired注释添加到构造函数中。

FooRepository

感谢您拥有@Repository注释Spring会注意到它可以创建所需对象的实例来创建@Autowired public FooJob(FooRepository fooRepo) { this.fooRepo = fooRepo; } 的实例。

2)您可以添加配置类。

@service

您必须在那里创建一个服务实例(@Configuration public class Config {} )。

我的拙见认为第一种选择看起来更好。

让我知道它是否有效!