Data retrieval using quartz

一笑奈何 提交于 2019-12-02 06:29:26

You are getting Null pointer exception because your Quartz job is not instantiated by the Spring and is running outside the springContext so all the beans that you are referencing inside it will be null. Now there are couple of ways to access the spring beans inside the quartz Job.

1)define the below bean in the applicationContext

<bean id="scheduler"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="configLocation">
     <value>classpath:quartz.properties</value>
  </property>
  <property name="applicationContextSchedulerContextKey">
    <value>applicationContext</value>
  </property>

get the above bean scheduler in your test class.code in your test class will become like below:

public void testMethod() throws SchedulerException
{
    JobDetail job = new JobDetail();
    job.setName("Retriving The Master Details");
    job.setJobClass(QuartzProcess.class);


    SimpleTrigger trigger = new SimpleTrigger();
    trigger.setName("Trigger For Retriving The Master Details");
    trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
    trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    trigger.setRepeatInterval(5000);


    scheduler.scheduleJob(job, trigger);
}

scheduler bean you need get in the main class in the usual way. you need not do the scheduler.start as the scheduler will be started by the spring containter.

In your QuartzProcess class,you need to add below method to get the applicationContext:

    public ApplicationContext getApplicationContext(JobExecutionContext context) throws Exception {
        ApplicationContext applicationContext = null;
        applicationContext = (ApplicationContext) context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
        if (applicationContext == null) {
            throw new JobExecutionException("No application context available in scheduler context for key \""
                                            + APPLICATION_CONTEXT_KEY
                                            + "\"");
        }
        return applicationContext;
    }

Then in your xecute method of the quartzprocess ,you need to do teh below code to get the required bean

  ApplicationContext ctx = getApplicationContext(context);
  QuartzProcess quartzProcess = (QuartzProcess)ctx.getBean("quartzProcess");
haju

If you are trying to created a scheduled job that updates your database how about using Spring Task.

Here is an example: How to stop jobs scheduled using spring task

Then just call your method that performs your database update.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!