您可以使用该Managed
界面。在下面的代码段中,我使用ScheduledExecutorService
来执行作业,但Quartz
如果您愿意,也可以使用。我更喜欢使用它,ScheduledExecutorService
因为它更简单,更容易......
第一步是注册您的托管服务。
environment.lifecycle().manage(new JobExecutionService());
第二步是写。
/**
* 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();
}
}
和工作本身
/**
* 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());
}
}
正如下面评论中提到的,如果你使用Runnable
,你可以Thread.getState()
. 请参阅获取当前在 Java 中运行的所有线程的列表。根据您连接应用程序的方式,您可能仍需要一些中间件。