初始化调度器
我们可以在Web应用中的配置文件web.xml里设置一个Quartz的Servlet-QuartzInitializerServlet:
<web-app>
<servlet>
<servlet-name>QuartzInitializer</servlet-name> <display-name>Quartz Initializer Servlet</display-name><servlet-class> org.quartz.ee.servlet.QuartzInitializerServlet </servlet-class> <load-on-startup>1</load-on-startup> <init-param> <param-name>config-file</param-name> <param-value>/some/path/my_quartz.properties</param-value> </init-param> <init-param> <param-name>shutdown-on-unload</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>start-scheduler-on-load</param-name> <param-value>true</param-value> </init-param> </servlet> <!-- other web.xml items here -->
</web-app>
说明:config-file参数值是StdSchedulerFactory用来实例化调度器的,可以把自己写的Quartz属性文件放在classPath即WEB-INF/classes路径下。
访问调度器
从Quartz1.5开始,QuartzInitializerServlet将自动储存StdSchedulerFactory实例在ServletContext里:
// 从Session中获得ServletContext
ServletContext ctx =
request.getSession().getServletContext();
// 从ServletContext中获得StdSchedulerFactory
StdSchedulerFactory factory = (StdSchedulerFactory)ctx.getAttribute(
QuartzFactoryServlet.QUARTZ_FACTORY_KEY);
// 从StdSchedulerFactory中获得Scheduler
Scheduler scheduler = factory.getScheduler();
// 启动Scheduler
scheduler.start();