我正在尝试跟进“ Quartz Scheduling框架工作”一书中提到的步骤“在Web应用程序中初始化Quartz ”示例。这是程序https://gist.github.com/5777d9f27c700e716a5a的链接。但是这个例子是关于Struts1框架的。
我们的是带有Hibernate 3.5 ORM的struts2框架。我应该如何配置Struts2上的确切步骤。任何帮助将不胜感激。
但是如果我在contextInitialized()方法中编写代码,我会得到异常“java.lang.RuntimeException:java.io.FileNotFoundException:src / hibernate.cfg.xml(没有这样的文件或目录)”
Xml config = new Xml("src/hibernate.cfg.xml", "hibernate-configuration");
Properties prop = new Properties();
prop.setProperty("org.quartz.dataSource.tasksDataStore.driver", config.child("session-
factory").children("property").get(1).content());
prop.setProperty("org.quartz.dataSource.tasksDataStore.URL", config.child("session-
factory").children("property").get(2).content());
prop.setProperty("org.quartz.dataSource.tasksDataStore.user", config.child("session-
factory").children("property").get(3).content());
prop.setProperty("org.quartz.dataSource.tasksDataStore.password", config.child("session-
factory").children("property").get(4).content());
prop.setProperty("org.quartz.dataSource.tasksDataStore.maxConnections", "20");
SchedulerFactory sf = new StdSchedulerFactory(prop);
Scheduler sched = sf.getScheduler();
答案 0 :(得分:4)
要在容器加载时初始化Scheduler,您可以执行此操作。
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzServletContextListener implements ServletContextListener
{
public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY";
private StdSchedulerFactory factory = null;
/**
* Called when the container is shutting down.
*/
public void contextDestroyed(ServletContextEvent sce)
{
try
{
factory.getDefaultScheduler().shutdown();
} catch (SchedulerException ex)
{
}
}
/**
* Called when the container is first started.
*/
public void contextInitialized(ServletContextEvent sce)
{
ServletContext ctx = sce.getServletContext();
try
{
factory = new StdSchedulerFactory();
// Start the scheduler now
factory.getScheduler().start();
ctx.setAttribute(QUARTZ_FACTORY_KEY, factory);
} catch (Exception ex)
{
}
}
}
在您的web.xml中,添加
<listener>
<description>A Listener Class to initialize Quartz Scheduler</description>
<listener-class>full_package_path.QuartzServletContextListener</listener-class>
</listener>
这基本上在容器加载时创建调度程序。然后,您可以使用我之前的帖子从StdSchedulerFactory
中检索StdSchedulerFactory
。
如果有问题,请告诉我。
答案 1 :(得分:0)
public class MyClass implements ServletContextAware
{
private ServletContext context;
public void setServletContext(ServletContext context)
{
this.context = context.
}
public String execute()
{
StdSchedulerFactory factory = (StdSchedulerFactory)context.getAttribute(QuartzFactoryServlet.QUARTZ_FACTORY_KEY);
// Retrieve the scheduler from the factory
Scheduler scheduler = factory.getDefaultScheduler();
}
}
希望这更清楚。