嗨,这是我的 Cron 调度程序
public class CronListener implements ServletContextListener {
Scheduler scheduler = null;
@Override
public void contextInitialized(ServletContextEvent servletContext) {
System.out.println("Context Initialized");
try {
// Setup the Job class and the Job group
JobDetail job = newJob(CronJob.class).withIdentity("CronQuartzJob",
"Webapp").build();
// This is what I've tried as well
/*
* JobDataMap jdm = new JobDataMap(); jdm.put("targetDAO",
* targetDAO);
*/
// Create a Trigger that fires every X minutes.
Trigger trigger = newTrigger()
.withIdentity("CronQuartzJob", "Sauver")
.withSchedule(
CronScheduleBuilder.cronSchedule
("0 0/1 * 1/1 * ? *")).build();
// Setup the Job and Trigger with Scheduler & schedule jobs
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContext) {
System.out.println("Context Destroyed");
try {
scheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
这是 Cron 作业本身
public class CronJob implements org.quartz.Job {
static Logger log = Logger.getLogger(CronJob.class.getName());
@Autowired
TargetDAO targetDAO;
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
try {
targetDAO.getAllTargets();
} catch (Exception e1) {
e1.printStackTrace();
}
log.info("webapp-rest cron job started");
try {
Utils.getProcessed();
} catch (Exception e) {
e.printStackTrace();
}
}
我想要做的是让 DAO 类每隔几个小时调用一些数据并通过它调用一个函数。但是当我通过DAO调用数据时,它总是返回空。
我发现我必须以某种方式映射 DAO,我在基于 xml 的 cron 作业中看到过,但我无法在这个作业中映射它。