Running Background Tasks In DropWizard with Guava

Recently, I wrote a RESTful web service in Java 8 using Dropwizard.
Dropwizard is a breath of fresh air, a simple, lightweight, getting-things-done approach to RESTful web service design. In this post I will demonstrate how to combine Dropwizard’s Managed objects with Guava’s concurrency primitives to write a simple background task for each of our instances

The Specifics

Guava provides com.google.common.util.concurrent.AbstractScheduledService,
an abstraction for a periodic task that runs at it’s own background thread at certain intervals and can be started and stopped from the main thread. Here is one that logs to the console every 5 seconds

public class ConsoleLoggingScheduledTask extends AbstractScheduledService {

    private final Logger LOGGER = LoggerFactory.getLogger(ScheduledSynchronizationService.class);

    @Override
    protected void runOneIteration() throws Exception {
        LOGGER.info("runOneIteration");
    }

    @Override
    protected AbstractScheduledService.Scheduler scheduler() {
        return AbstractScheduledService.Scheduler.newFixedRateSchedule(0, 5, TimeUnit.SECONDS);
    }
}

Dropwizard provides the Managed interface for objects that need to be started
and stopped as the application instance is started or stopped.
It is easy to create a container/adapter for an AbstractScheduledService subclass like the one in the above example and enable it to be managed by Dropwizard.

public class ManagedPeriodicTask implements Managed {

    private final Logger LOGGER = LoggerFactory.getLogger(ManagedPeriodicTask.class);
    private final AbstractScheduledService periodicTask;

    public ManagedPeriodicTask(AbstractScheduledService ) {
        this.periodicTask = periodicTask;
    }

    @Override
    public void start() throws Exception {
        periodicTask.startAsync().awaitRunning();
    }

    @Override
    public void stop() throws Exception {
        periodicTask.stopAsync().awaitTerminated();
    }
}

Then on the run method of our Application subclass we can just do the following

final ConsoleLoggingScheduledTask periodicTask = new ConsoleLoggingScheduledTask();
final Managed managedImplementer = new ManagedPeriodicTask(periodicTask);
environment.lifecycle().manage(managedImplementer);

So, there you have it! A simple way to create background (semi) periodic tasks that are managed (started and stopped) by dropwizard, for usages such as gossip, consensus or asynchronous tasks like emailing and logging.

Published by pgk

Person

%d bloggers like this: