reload servlet once a month

不羁的心 提交于 2019-12-03 21:19:28

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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!