Running async jobs in dropwizard, and polling thei

2019-02-15 15:58发布

问题:

In dropwizard, I need to implement asynchronous jobs and poll their status. I have 2 endpoints for this in 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 to use quartz to start job, but only single time and without repeating. And when requesting status, I will get trigger status. But the idea of using quartz for none-scheduled usage looks weird. Is there any better approaches for this? Maybe dropwizard provides better tools itself? Will appriciate any advices.

UPDATE: I also looking at https://github.com/gresrun/jesque, but can not find any way to poll the status of running job.

回答1:

You can use the Managed interface. In the snippet below I am using the ScheduledExecutorService to exuecute jobs, but you can use Quartz instead if you like. I prefer working with ScheduledExecutorService as it is simpler and easier...

first step is to register your managed service.

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

Second step is to write it.

/**
 * 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 job 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(). Please refer to Get a List of all Threads currently running in Java. You may still need some intermediary pieces depending on how you're wiring you application.