使用guava AbstractScheduledService(Using guava AbstractScheduledService)
我正在尝试使用guava AbstractScheduledService定期执行一些任务:
public class MyService extends AbstractScheduledService { public MyService() { } @Override protected void runOneIteration() { doStuff(); } private void doStuff() { // Do stuff } @Override protected Scheduler scheduler() { return Scheduler.newFixedRateSchedule(0, 8, TimeUnit.HOURS); } }
所以这项服务应该每8小时定期执行一些任务,但实际上并不是这样。 继承的
isRunning()
方法返回false,并且永远不会调用runOneIteration()
方法。我已经设法通过从我的服务构造函数调用
startAsync()
方法(从父类继承startAsync()
来使它工作,但我没有看到任何引用说这是应该工作的方式。我错过了什么吗? 这是
AbstractScheduledService
工作方式吗?I'm trying to execute some task periodically using guava AbstractScheduledService :
public class MyService extends AbstractScheduledService { public MyService() { } @Override protected void runOneIteration() { doStuff(); } private void doStuff() { // Do stuff } @Override protected Scheduler scheduler() { return Scheduler.newFixedRateSchedule(0, 8, TimeUnit.HOURS); } }
So this service should execute some task periodically every 8 hours but it never actually does. The inherited
isRunning()
method returns false and therunOneIteration()
method never gets invoked.I have managed to make it work by calling the
startAsync()
method (inherited from parent class) from my service constructor but I don't see any reference saying this is the way it should work.Have I missed something here? Is this the way the
AbstractScheduledService
works?
原文:https://stackoverflow.com/questions/25499811
最满意答案
AbstractScheduledServiced
实现Service 。 Service接口描述了生命周期方法,包括startAsync
。 ServiceState枚举文字包含有关其含义的文档。 处于NEW
状态的服务(刚刚创建):处于此状态的服务处于非活动状态。 它做的工作量极少,占用资源极少。
要使服务执行某些有用的操作,您必须将其转换为
RUNNING
状态此状态下的服务正在运行。
这就是为什么你必须在它做任何事之前启动服务的原因。
我还建议不要从构造函数中调用startAsync,而是从创建
MyService
实例的代码调用它。 在构造函数中产生如此严重的副作用(创建Threads)很少是预期的事情。
AbstractScheduledServiced
implements Service. The Service interface describes lifecycle methods includingstartAsync
. The ServiceState enum literals contain documentation on what they mean. A Service inNEW
state (just created):A service in this state is inactive. It does minimal work and consumes minimal resources.
For the Service to do something useful you have to transition it to the state
RUNNING
A service in this state is operational.
That's why you have to start the Service before it does anything.
I would also advise against calling startAsync from the constructor and instead calling it from the Code that creates your
MyService
instance. It is rarely an expected thing to have such heavy side effects (creation of Threads) in the constructor.