【发布时间】:2009-03-16 13:23:20
【问题描述】:
我有一个 Java servlet 程序,它在 tomcat 启动时启动。我已经提到该程序在启动时加载。我没有使用任何 HTTP 请求或响应。
我需要的是我需要将程序作为服务运行或需要在特定时间间隔自动刷新。怎么做?有人可以帮助我!
谢谢, 戈帕尔。
【问题讨论】:
-
自动刷新是什么意思? tomcat 自己做这个。
标签: java
我有一个 Java servlet 程序,它在 tomcat 启动时启动。我已经提到该程序在启动时加载。我没有使用任何 HTTP 请求或响应。
我需要的是我需要将程序作为服务运行或需要在特定时间间隔自动刷新。怎么做?有人可以帮助我!
谢谢, 戈帕尔。
【问题讨论】:
标签: java
Quartz 是个好主意,但根据您的需要,可能有点矫枉过正。我认为你真正的问题是试图将你的服务塞进一个 servlet,而你实际上并没有在监听传入的 HttpServletRequests。相反,请考虑使用 ServletContextListener 来启动您的服务,并按照 Maurice 的建议使用 Timer:
web.xml:
<listener>
<listener-class>com.myCompany.MyListener</listener-class>
</listener>
然后你的班级看起来像这样:
public class MyListener implements ServletContextListener {
/** the interval to wait per service call - 1 minute */
private static final int INTERVAL = 60 * 60 * 1000;
/** the interval to wait before starting up the service - 10 seconds */
private static final int STARTUP_WAIT = 10 * 1000;
private MyService service = new MyService();
private Timer myTimer;
public void contextDestroyed(ServletContextEvent sce) {
service.shutdown();
if (myTimer != null)
myTimer.cancel();
}
public void contextInitialized(ServletContextEvent sce) {
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
myService.provideSomething();
}
},STARTUP_WAIT, INTERVAL
);
}
}
【讨论】:
我建议您使用Quartz。您可以使用石英定义计划作业。
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzTest {
public static void main(String[] args) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
【讨论】:
每次 .war 文件更改时,tomcat 都会自动刷新
【讨论】:
我有时会使用计时器来定期发出 HTTP 请求:
timer = new Timer(true);
timer.scheduleAtFixedRate(
new TimerTask() {
URL url = new URL(timerUrl);
public void run() {
try {
url.getContent();
} catch (IOException e) {
e.printStackTrace();
}
}
},
period,
period);
【讨论】: