JavaQuartz产生未处理的空指针异常
因此,我在不同的Spring配置文件上设置了两个调度程序。当我运行Spring调度器时,一切正常,但他们希望我实现Quartz
这里有一个职业分类:
@Profile("quartz")
@Component
public class SampleJob implements Job {
@Autowired
private GetDataServiceQuartz getDataServiceQuartz;
public SampleJob() {
}
public SampleJob(GetDataServiceQuartz getDataServiceQuartz) {
this.getDataServiceQuartz = getDataServiceQuartz;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
this.getDataServiceQuartz.storeData();
}
}
正在引发一个错误:
org.quartz.SchedulerException: Job threw an unhandled exception.
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
Caused by: java.lang.NullPointerException: null
at com.example.blockchaininfo.services.Quartz.SampleJob.execute(SampleJob.java:27) ~[classes/:na]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
... 1 common frames omitted
正在该特定行上抛出nullPointerException
:
this.getDataServiceQuartz.storeData();
我一试着打印this.getDataServiceQuartz
,它就会打印null
完成所有后续工作的班级:
@Slf4j
@Service
@Profile("quartz")
public class GetDataServiceQuartz{
constructorHere();
public void storeData(){
try {
String hashrateFromApi = this.getNetworkHashrateFromApi("http://public.turtlenode.io:11898/getinfo");
OffsetDateTime date = OffsetDateTime.now();
this.saveNetworkHashrateNewEntity(hashrateFromApi, date);
this.storePoolDataToDB(this.getPoolsListFromJson(), retrieveNetworkIdForPoolDefinition(date));
} catch (HttpServerErrorException e){
log.info("Network Server error e1: " + e);
} catch (ResourceAccessException e2){
log.info("Network resource access exception: " + e2);
} catch (IOException e3) {
log.info("" + e3);
} catch (InterruptedException e4){
log.info("" + e4);
}
}
...all other methods to acquire stuff.
和石英配置
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){
this.startQuartzScheduling();
}
public void startQuartzScheduling () {
JobDetail job = JobBuilder.newJob(SampleJob.class)
.withIdentity("dummyJobName", "group1").build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5).repeatForever())
.build();
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e){
log.info("" + e);
}
}
我错过了什么?如何正确地注入一个应该安排其方法的类
# 1 楼答案
我相信这是因为quartz
JobBuilder
创建了SampleJob
的新实例,而不是使用带有自动连接字段的已创建实例。由于它使用默认构造函数作为结果,所以您有空指针解决这个问题的一个方法是将
GetDataServiceQuartz
放到调度程序上下文中描述here
因此,要放置数据,您需要调用:
在执行任务时:
我认为,另一个更方便的方法是将它放到
JobDataMap
上,您的SampleJob
将提供:执行任务时:
完整的示例可以在here中找到