インターフェイスを使用できManaged
ます。以下のスニペットでは、ScheduledExecutorService
ジョブを実行するために を使用していますが、必要Quartz
に応じて代わりに使用することもできます。ScheduledExecutorService
よりシンプルで簡単なため、私はで作業することを好みます...
最初のステップは、マネージド サービスを登録することです。
environment.lifecycle().manage(new JobExecutionService());
2番目のステップは、それを書くことです。
/**
* 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 で現在実行中のすべてのスレッドのリストを取得するを参照してください。アプリケーションの配線方法によっては、まだいくつかの中間部分が必要になる場合があります。