Using guava AbstractScheduledService

I am trying to accomplish 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);
    }

}

      

Thus, this service has to do some task periodically every 8 hours, but this never happens. The inherited method isRunning()

returns false, and the method runOneIteration()

never runs.

I managed to get it to work by calling a method startAsync()

(inherited from the parent class) from my service constructor, but I can't see the link saying this is how it should work.

Did I miss something? Is that how it works AbstractScheduledService

?

+3


source to share


1 answer


AbstractScheduledServiced

implements Service . The service interface describes lifecycle methods including startAsync

. ServiceState lists literals about what they mean. Service in NEW

state (just created):

The service is inactive in this state. It does minimal work and consumes minimal resources.

In order for the Service to do something useful, you need to transfer it to the state RUNNING



The service is running in this state.

This is why you must start the service before it does anything.

I would also advise not to call startAsync from the constructor and instead call it from the code that creates your instance MyService

. A rarely expected thing has such heavy side effects (thread creation) in the constructor.

+4


source







All Articles