3

I am using quartz in my apache isis project for scheduling. I have a class MyJob which implements org.quartz.Job and it has method execute which is called when scheduler triggers at given time.

My problem is, I have a class DemoService and it has a method showDemo() which I want to call from the execute method. But when the scheduler runs, it throws Null Pointer Exception at demoService.showDemo().

I have not been able to inject any service in that class. It always gives NPE. How can I inject a service into the MyJob class?

Here is the code:-

public class MyJob implements Job {

    @Inject
    DemoService demoService;

    public MyJob() {

    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        demoService.showDemo();
    }
}
Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29
Siddhesh Phatak
  • 198
  • 1
  • 2
  • 11

2 Answers2

1

The easiest approach is to put the logic you want to run in a subclass of AbstractIsisSessionTemplate, and then instantiate and execute it from your quartz job.

This technique is used by the Incode Platform's quartz job to run background commands, see here; the quartz module shows this from the quartz perspective (which I think you already have figured out).

HTH Dan

Dan Haywood
  • 2,215
  • 2
  • 17
  • 23
0

Try this NullPointerException while deploying Quartz in Spring Boot

You need to use SpringBeanJobFactory to create Job with Spring's autowired beans.

class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory;

public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
}

@Override
public Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
   final Object job = super.createJobInstance(bundle);
   beanFactory.autowireBean(job);  //the magic is done here
   return job;
}

} And then when you do

SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
scheduler = schedFact.getScheduler();

AutowiringSpringBeanJobFactory autowiringSpringBeanJobFactory = new AutowiringSpringBeanJobFactory();
autowiringSpringBeanJobFactory.setApplicationContext(applicationContext);
scheduler.setJobFactory(autowiringSpringBeanJobFactory);
Srinivas
  • 400
  • 1
  • 8