Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

servlets - Retrieve servletContext reference in quartz scheduler

I am using Quartz Scheduler with my spring 3.0 based application. I am successfully able to create new schedulers and they are working fine.

I have seen thus reference.

But.. I am not able to retrieve servletContext in my quartz job file. can anyone help me for How to retrieve servletContext reference in executeInternal() method ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had a similar need. I sorted it out in a similar fashion to the solution presented here. In my servlet context listener I am setting the servlet context using the job data map object which then is set for a job:

    @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);
        }
    }

Then inside my job I am doing this:

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

EDIT: Also since you mention that you are using Spring I found this link, where in the last post a guy mentions to implement ServletContextAware. Personally, I would go with the JobDataMap, since that is its role.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...