我有一个Java servlet程序,它在tomcat启动时启动。我在启动时提到了程序加载。我没有使用任何HTTP请求或响应。
我需要的是我需要将程序作为服务运行,或者需要在特定时间间隔内自动刷新。怎么做?有人可以帮我!
谢谢, 戈帕尔。
答案 0 :(得分:3)
Quartz是一个好主意,但根据您的需要可能会有点过分。我认为你真正的问题是当你实际上没有收听传入的HttpServletRequests时,试图将你的服务塞进一个servlet。相反,考虑使用ServletContextListener启动您的服务,以及一个Timer,正如Maurice建议的那样:
的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
);
}
}
答案 1 :(得分:1)
我建议您使用Quartz。您可以使用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();
}
}
}
答案 2 :(得分:0)
每次.war文件更改时,tomcat都会自动刷新
答案 3 :(得分:0)
我有时会使用计时器定期发出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);