2017-05-26 21 views
0

你好,這是我的Cron調度在計劃作業數據呼叫使用DAO類

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作業中看到過,但我無法將其映射到此映射中。

+1

您的cronjob不是春豆所以道不能被自動裝配。嘗試向CronJob類中添加@ @ Component – StanislavL

+0

它沒有工作,我甚至將它添加到servlet-context以進行組件掃描,輸出仍然是java.lang.NullPointerException – Aamir

回答

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/