Running asynchronous jobs in dropwizard and polling their status

In dropwizard, I need to implement asynchronous jobs and poll their status. I have 2 endpoints for this in a resource:

@Path("/jobs") @Component public class MyController { @POST @Produces(MediaType.APPLICATION_JSON) public String startJob(@Valid MyRequest request) { return 1111; } @GET @Path("/{jobId}") @Produces(MediaType.APPLICATION_JSON) public JobStatus getJobStatus(@PathParam("id") String jobId) { return JobStatus.READY; } } 

I am considering using quartz to get started, but only once and without repetition. And when you request the status, I get the status of the trigger. But the idea of ​​using quartz for unplanned use looks strange. Are there any better approaches for this? Maybe dropwizard provides better tools? Any advice will be approved.

UPDATE: I also look at https://github.com/gresrun/jesque , but cannot find a way to query the status of the work in progress.

+1
source share
1 answer

You can use the Managed interface. In the snippet below, I use ScheduledExecutorService to do the tasks, but you can use Quartz instead if you want. I prefer to work with ScheduledExecutorService as it is simpler and simpler ...

The first step is to register the managed service.

 environment.lifecycle().manage(new JobExecutionService()); 

The second step is to write it down.

 /** * A wrapper around the ScheduledExecutorService so all jobs can start when the server starts, and * automatically shutdown when the server stops. * @author Nasir Rasul {@literal nasir@rasul.ca } */ public class JobExecutionService implements Managed { private final ScheduledExecutorService service = Executors.newScheduledThreadPool(2); @Override public void start() throws Exception { System.out.println("Starting jobs"); service.scheduleAtFixedRate(new HelloWorldJob(), 1, 1, TimeUnit.SECONDS); } @Override public void stop() throws Exception { System.out.println("Shutting down"); service.shutdown(); } } 

and the work itself

 /** * A very simple job which just prints the current time in millisecods * @author Nasir Rasul {@literal nasir@rasul.ca } */ public class HelloWorldJob implements Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { System.out.println(System.currentTimeMillis()); } } 

As mentioned in the comment below, if you use Runnable , you can Thread.getState() . See Get a list of all topics currently running in Java . You may need some intermediate parts depending on how you connect the application.

+4
source

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


All Articles