0

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

4

1 回答 1

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/

于 2017-05-26T12:05:30.393 回答