me1*_*111 2 jobs spring dropwizard jesque
在dropwizard中,我需要实现异步作业并轮询其状态。我在资源中有2个端点:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用石英来开始工作,但只能一次,并且无需重复。当请求状态时,我将获得触发器状态。但是,将石英用于非预定用途的想法看起来很奇怪。有没有更好的方法呢?也许dropwizard本身提供了更好的工具?将提出任何建议。
更新:我也在看https://github.com/gresrun/jesque,但是找不到任何方法来轮询正在运行的作业的状态。
您可以使用该Managed界面。在下面的代码段中,我使用ScheduledExecutorService来执行工作,但Quartz如果愿意,可以改用。我更喜欢使用ScheduledExecutorService它,因为它更简单,更容易...
第一步是注册您的托管服务。
environment.lifecycle().manage(new JobExecutionService());
Run Code Online (Sandbox Code Playgroud)
第二步是编写它。
/**
* 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();
}
}
Run Code Online (Sandbox Code Playgroud)
和工作本身
/**
* 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());
}
}
Run Code Online (Sandbox Code Playgroud)
如以下评论中所述,如果您使用Runnable,则可以Thread.getState()。请参考获取当前正在Java中运行的所有线程的列表。您可能仍需要一些中间件,具体取决于您连接应用程序的方式。
| 归档时间: |
|
| 查看次数: |
2796 次 |
| 最近记录: |