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 [email protected]} */ 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 [email protected]} */ 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.