Running async jobs in dropwizard, and polling their status

前端 未结 1 1814
独厮守ぢ
独厮守ぢ 2021-01-07 05:37

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         


        
1条回答
  •  天命终不由人
    2021-01-07 06:21

    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 Runnable is used
         * to create a thread, starting the thread causes the object's
         * run method to be called in that separately executing
         * thread.
         * 

    * The general contract of the method run 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.

    0 讨论(0)
提交回复
热议问题