Dropwizard ScheduledExecutorService

user3280180 picture user3280180 · Oct 23, 2014 · Viewed 7.4k times · Source

In my case I need to run some scheduled tasks (e.g. every minute) doing some checks in DB and if needed some subtasks. This should be no DB health-check!

DW documentation says:

"It should be noted that Environment has built-in factory methods for ExecutorService and ScheduledExecutorService instances which are managed. See LifecycleEnvironment#executorService and LifecycleEnvironment#scheduledExecutorService for details."

Does anyone knows how to implement this in DW? Trying to play around with DW code possibilities, I found this:

String nameFormat = "?What should this string contain?";
ScheduledExecutorServiceBuilder sesBuilder = environment.lifecycle().scheduledExecutorService(nameFormat);
ScheduledExecutorService ses = sesBuilder.build();
Runnable alarmTask = new AlarmTask();
ses.scheduleWithFixedDelay(alarmTask, 0, 5, TimeUnit.SECONDS);

Is this the correct way in DW to do this? BTW a runnable dummy:

  private static final class AlarmTask implements Runnable {
      DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      Calendar cal = Calendar.getInstance();
        @Override public void run() {
          ++fCount;

            cal = Calendar.getInstance();
            System.out.println(fCount + "x BEEP:" + dateFormat.format(cal.getTime()));
        }
        private int fCount;
      }

Whats the purpose of the initial name and is it used somewhere? Hope someone can help.

Answer

krisr picture krisr · Oct 27, 2014

I'm doing pretty much the same thing in a Dropwizard app to run a job periodically. There are projects such as dropwizard-jobs and dropwizard-quartz, but this seemed to work fine for my simple needs.

The ScheduledExecutorServiceBuilder passes the nameFormat to the ThreadFactoryBuilder as a pattern for naming the threads. The docs for that might be helpful to you: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/ThreadFactoryBuilder.html#setNameFormat(java.lang.String)