001package io.prometheus.metrics.core.util;
002
003import java.util.concurrent.CountDownLatch;
004import java.util.concurrent.Executors;
005import java.util.concurrent.ScheduledExecutorService;
006import java.util.concurrent.ScheduledFuture;
007import java.util.concurrent.ThreadFactory;
008import java.util.concurrent.TimeUnit;
009
010/**
011 * Used for scheduling maintenance tasks like purging outdated Exemplars or resetting native
012 * histograms.
013 */
014public class Scheduler {
015
016  private static class DaemonThreadFactory implements ThreadFactory {
017    @Override
018    public Thread newThread(Runnable runnable) {
019      Thread thread = new Thread(runnable);
020      thread.setDaemon(true);
021      return thread;
022    }
023  }
024
025  private static final ScheduledExecutorService executor =
026      Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
027
028  public static ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
029    return executor.schedule(command, delay, unit);
030  }
031
032  /** For unit test. Wait until the executor Thread is running. */
033  @SuppressWarnings("FutureReturnValueIgnored")
034  public static void awaitInitialization() throws InterruptedException {
035    CountDownLatch latch = new CountDownLatch(1);
036    Scheduler.schedule(latch::countDown, 0, TimeUnit.MILLISECONDS);
037    latch.await();
038  }
039}