How to start a service at a specific time using the JSP / Servlets application?

I am developing a JSP / Servlets application and I want to run the service at a specific time, for example:

For each day at 10:00 in the morning, remove all the binding from the "attachment" table in the database, where the column X == NULL.

How can I do this in a JSP / Servlets application? I use Glassfish as a server.

+4
source share
3 answers

Deploy ServletContextListener ; in the contextInitialized method:

 ServletContext servletContext = servletContextEvent.getServletContext(); try{ // create the timer and timer task objects Timer timer = new Timer(); MyTimerTask task = new MyTimerTask(); //this class implements Callable. // get a calendar to initialize the start time Calendar calendar = Calendar.getInstance(); Date startTime = calendar.getTime(); // schedule the task to run hourly timer.scheduleAtFixedRate(task, startTime, 1000 * 60 * 60); // save our timer for later use servletContext.setAttribute ("timer", timer); } catch (Exception e) { servletContext.log ("Problem initializing the task that was to run hourly: " + e.getMessage ()); } 

Edit your web.xml to have a link to your listener implementation:

 <listener> <listener-class>your.package.declaration.MyServletContextListener</listener-class> </listener> 
+1
source

You are running a Glassfish Java EE server, so you must have access to the EJB timer service.

Here is an example:

http://java-x.blogspot.com/2007/01/ejb-3-timer-service.html

I used the previous version of the API on JBoss and it worked fine.

Currently, we tend to abandon quartz in war and use it for timed execution, so it also works on our Jetty development examples.

+4
source

You need to check if the server implementation supports such tasks. If it does not support it or you want to be server independent, then run the ServletContextListener to connect to the webapp launch and use the ScheduledExecutorService to complete the task at the specified time and intervals.

Here is an example of the main launch:

 public class Config implements ServletContextListener { private ScheduledExecutorService scheduler; public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Task(), millisToNext1000, 1, TimeUnit.DAYS); } public void contextDestroyed(ServletContextEvent event) { scheduler.shutdown(); } } 

Where Task implements Callable and millisToNext1000 - the number of milliseconds in the next 10:00. You can use Calendar or JodaTime to calculate this. As an alternative to non-Java, you can also use Quartz .

+3
source

Source: https://habr.com/ru/post/1312266/


All Articles