检索quartz调度程序中的servletContext引用

Gun*_*hah 5 servlets quartz-scheduler

我在基于Spring 3.0的应用程序中使用Quartz Scheduler.我成功地能够创建新的调度程序,它们工作正常.

我见过这样的参考.

但是..我无法在我的石英作业文件中检索servletContext.任何人都可以帮助我如何在executeInternal()方法中检索servletContext引用?

Gunjan Shah,thx.

Bor*_*oro 6

我有类似的需求.我以与此处提供的解决方案类似的方式对其进行了分类. 在我的servlet上下文监听器中,我使用作业数据映射对象设置servlet上下文,然后为作业设置该对象:

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            //Create & start the scheduler.
            StdSchedulerFactory factory = new StdSchedulerFactory();
            factory.initialize(sce.getServletContext().getResourceAsStream("/WEB-INF/my_quartz.properties"));
            scheduler = factory.getScheduler();
            //pass the servlet context to the job
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("servletContext", sce.getServletContext());
            // define the job and tie it to our job's class
            JobDetail job = newJob(ImageCheckJob.class).withIdentity("job1", "group1").usingJobData(jobDataMap).build();
            // Trigger the job to run now, and then repeat every 3 seconds
            Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow()
                  .withSchedule(simpleSchedule().withIntervalInMilliseconds(3000L).repeatForever()).build();
            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);
            // and start it off
            scheduler.start();
        } catch (SchedulerException ex) {
            log.error(null, ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在我的工作中我这样做:

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        ServletContext servletContext = (ServletContext) context.getMergedJobDataMap().get("servletContext");
        //...
    }
Run Code Online (Sandbox Code Playgroud)

编辑: 此外,既然你提到你正在使用Spring 我找到了这个链接,在上一篇文章中,一个人提到实现ServletContextAware.就个人而言,我会选择JobDataMap,因为这是它的作用.