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 histograms. 012 */ 013public class Scheduler { 014 015 private static class DaemonThreadFactory implements ThreadFactory { 016 public Thread newThread(Runnable runnable) { 017 Thread thread = new Thread(runnable); 018 thread.setDaemon(true); 019 return thread; 020 } 021 } 022 023 private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory()); 024 025 public static ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { 026 return executor.schedule(command, delay, unit); 027 } 028 029 /** 030 * For unit test. Wait until the executor Thread is running. 031 */ 032 public static void awaitInitialization() throws InterruptedException { 033 CountDownLatch latch = new CountDownLatch(1); 034 Scheduler.schedule(latch::countDown, 0, TimeUnit.MILLISECONDS); 035 latch.await(); 036 } 037}