Reputation: 2072
I would like to execute the following JAVA code only once when I enter to welcome.jsp page.
welcome.jsp:
<%WeeklyScheduledMail wsm = WeeklyScheduledMail.INSTANCE;
wsm.startThread(); %>
So, if a user access to the website once the server is initiated, that code can be used once, and the other users who log in and access to welcome.jsp will not execute that JAVA code.
First, I tried to implement the Singleton pattern with enum, I thought it would be enough but it did not work. I also tried the Synchronized keyword for the methods but nothing...
I'm sure I did something wrong or there is a better way to do what I want to do.
Some portions of the code:
WeeklyScheduledMail.java:
public enum WeeklyScheduledMail{
INSTANCE;
public void startThread() {
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
Runnable task = new TaskSendEmail();
int initialDelay = 0;
int periodicDelay = 10;
scheduler.scheduleAtFixedRate(task, initialDelay, periodicDelay,
TimeUnit.SECONDS);
}
}
TaskSendEmail.java:
public class TaskSendEmail implements Runnable{
public void run() {
System.out.println("Hello: "+System.currentTimeMillis());
}
}
Upvotes: 0
Views: 1112
Reputation: 45309
You're looking into the incorrect concept to run application initialization code. JSPs and other resources exposed to the user aren't designed for this. Even if you can force some lazy initialization logic, there will still be avoidable overhead.
What you're looking for is provided by JavaEE: a context listener, which is invoked once on application startup to notify your application that the context has been initialized:
public class MyContextListener implements javax.servlet.ServletContextListener {
private static fWeeklyScheduledMail wsm =
weeklyScheduledMail.INSTANCE;
@Override
public void contextInitialized(ServletContextEvent sce) {
wsm.startThread();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
wsm.stopThread();
}
}
This listener must then be registered in the web.xml
deployment descriptor (under web-app
):
<listener>
<listener-class>my.packg.MyContextListener</listener-class>
</listener>
The above code and configuration will cause your schedule to run once, when the application starts.
Upvotes: 1