I am developing server side web services code. I am using JAX-RS as development framework.
So far I have created model classes and resources class that responds requested data to client.
Sample resource method...
@GET
@Path("/{userId}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserDetails(@PathParam("userId") long id) {
..
// some code here //
..
}
Basically, server responds the data or do some operations depends on the URI is been called by the client.
I want to make Http POST request to third-party server at every two minutes from the moment server starts. But I dont know where should I write that code (as I said, methods executions depends on the URI is been called).
So, where should I write the code that starts executing when the server starts and ends when server stops.
How to send Http request at every two minutes interval ?
You should be able to do that with a combination of Quartz and ServletContextListener.
You will need to create a job, trigger and scheduler to make your code run after every two minutes and a listener class that implements ServletContextListener interface.
Your code would look something like this:
Job Class:
package com.example;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class ExampleJob implements Job
{
public void execute(JobExecutionContext context) throws JobExecutionException {
// Code to make POST call here
}
ServletContextListener
package com.example;
public class ExampleListener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContext context) {
JobDetail job = JobBuilder.newJob(ExampleJob.class)
.withIdentity("exampleJob", "group").build();
// Trigger
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("exampleTrigger", "group")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(120).repeatForever())
.build();
// Scheduler
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
And add this in web.xml:
<listener>
<listener-class>com.example.ExampleListener</listener-class>
</listener>
or if you are using servlet container 3.x, you can skip the web.xml modification by annotating the listener class with @WebListener
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.