开发者

reload servlet once a month

How can a reload a servlet once a month?

We got some data which will change once a month, the data is for the servlet, but we don't need to save the data into DB, instead we want to make it a configuration file which will be replaced once a month, how can I do this?

I know that the servlet's lifecycle policy is controlled by the container, I am using websphere 7, but I don't know if there is a way to configure that in websphere.

Will calling the destory() method affect the running instances of serv开发者_开发知识库let? AFAIK, the servlet is multi-threaded.


Don't use a servlet to store the data. Rather store the data as an attribute of the ServletContext. You can do it with help of a ServletContextListener. The very same listener class can also be used to reload the data at timed intervals with help of ScheduledExecutorService.

Here's a kickoff example:

public class Config implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Data data = new Data();
        event.getServletContext().setAttribute("data", data);
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Reloader(data), 0, 30, TimeUnit.DAYS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

(note that there's no TimeUnit.MONTH, so this is the best you can get for "once a month")

Where the Reloader class look like this:

public class Reloader implements Runnable {

    private Data data;

    public Reloader(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        data.reload();
    }

}

After registering the listener in /WEB-INF/web.xml as follows

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

it will create the Data instance and a single thread scheduler which executes the data.reload() every 30 days and you can access the Data instance in every servlet as follows:

Data data = (Data) getServletContext().getAttribute("data");

and in JSPs as follows:

${data}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜