Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using guava AbstractScheduledService

Tags:

java

guava

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 the runOneIteration() 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?

like image 231
forhas Avatar asked Oct 17 '25 13:10

forhas


1 Answers

AbstractScheduledServiced implements Service. The Service interface describes lifecycle methods including startAsync. The ServiceState enum literals contain documentation on what they mean. A Service in NEW 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.

like image 53
Patrick Huy Avatar answered Oct 20 '25 03:10

Patrick Huy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!