在Cron Job中使用DAO类进行数据调用

时间:2017-05-26 09:28:04

标签: java spring quartz data-access-object

嗨,这是我的Cron Scheduler

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 Job本身

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作业中看到了,但是我无法在这个映射中映射它。

1 个答案:

答案 0 :(得分:0)

这不是答案,而是一种解决方法, 我所做的是创造了一个新的课程

@EnableScheduling
@Component
public class SpringCronJob {

private static Logger log = Logger.getLogger(SpringCronJob.class.getName());

@Autowired
TargetDAO targetDAO;

@Scheduled(fixedRate = 15000)
public void getPostedTargets() {
      try {
          log.info(targetDAO.getAllTargets());
      } catch (Exception e) {
            // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }
}

它不需要任何其他东西,没有调度程序,您只需将其添加到组件扫描中

这就是我的理由 http://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/