Fire Quartz manually By Spring controller

670 views Asked by At

I use the following configuration class to integrate spring framework with Quartz,It works fine,but the job fires dynamically once the application has started because I use @Configuration annotation,I want to fire the job manually by controller and ui. How to Fire Quartz manually By Spring controller?

Quartz configuration class

@Configuration
public class QuartzConfig {

@Autowired
private PlatformTransactionManager transactionManager;

@Autowired
private ApplicationContext applicationContext;

@Bean
public SchedulerFactoryBean quartzScheduler() {
    SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

    quartzScheduler.setTransactionManager(transactionManager);
    quartzScheduler.setOverwriteExistingJobs(true);

    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    quartzScheduler.setJobFactory(jobFactory);

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

    quartzScheduler.setTriggers(triggers);

    return quartzScheduler;
}

@Bean
public JobDetailFactoryBean processMyJob() {
    JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
    jobDetailFactory.setJobClass(HelloJob.class);
    jobDetailFactory.setDurability(true);
    return jobDetailFactory;
}

@Bean
public CronTriggerFactoryBean processMyJobTrigger() {
    CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
    cronTriggerFactoryBean.setJobDetail(processMyJob().getObject());
    cronTriggerFactoryBean.setCronExpression("0 0/1 * * * ?");
    return cronTriggerFactoryBean;
}

}

Quartz job

@Service
@Transactional
public class HelloJob implements Job{

@Inject
TestrecordRepository testrecordRepository;
@Inject
ScoreRepository scoreRepository;


public void execute(JobExecutionContext context)
        throws JobExecutionException {
            System.out.println("Hello Quartz!");    
            List<Testrecord> records=testrecordRepository.findAll();
            for(Testrecord t:records){
                Testrecord testrecord = new Testrecord();
                testrecord.setValue_integer(t.getValue_integer());
                testrecord.setId(t.getId());
                RuleExecutor ruleExecutor = new RuleExecutor();
                Score score= ruleExecutor.processRules(testrecord);
                scoreRepository.save(score);    
            }

        }

}

1

There are 1 answers

0
michal On

From the controller you need to get access to SchedulerFactoryBean, then take scheduler and trigger job you like.

Scheduler scheduler = (Scheduler)   getApplicationContext().getBean("schedulerFactoryBean");

scheduler.triggerJob(JobKey jobKey)