If present, calls the servlet’s service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.
The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:
<servlet servlet-name=”test.HelloWorld”>
<run-at>0:00, 6:00, 12:00, 18:00</run-at>
</servlet>
In Java web applications, servlets are typically configured to start automatically when the web container (such as Tomcat, Jetty, or another servlet container) is initialized. There are several ways to achieve this:
- Using Servlet 3.0 Annotations: In Servlet 3.0 and later versions, you can use annotations to declare a servlet and specify that it should be loaded on application startup. You can use the
@WebServlet
annotation with theloadOnStartup
attribute.javaimport javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebInitParam;
public class MyServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
// Initialization code here
}
// Other servlet methods here
}In this example,
loadOnStartup
is set to 1, indicating that the servlet should be loaded on application startup. - Using the web.xml Deployment Descriptor: If you are not using Servlet 3.0 annotations, you can configure the servlet in the
web.xml
deployment descriptor. Set the<load-on-startup>
element to a positive integer value.xml<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
The
<load-on-startup>
element specifies the order in which the servlet should be loaded on application startup.
By using one of these methods, you ensure that your servlet is initialized automatically when the web application starts. The specified loadOnStartup
value or order in the deployment descriptor determines the order of initialization if multiple servlets are configured to start on application startup.