java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.5k)|赞(0)|评价(0)|浏览(160)

本文整理了Java中java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate()方法的一些代码示例,展示了ScheduledExecutorService.scheduleAtFixedRate()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ScheduledExecutorService.scheduleAtFixedRate()方法的具体详情如下:
包路径:java.util.concurrent.ScheduledExecutorService
类名称:ScheduledExecutorService
方法名:scheduleAtFixedRate

ScheduledExecutorService.scheduleAtFixedRate介绍

[英]Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
[中]创建并执行一个周期性动作,该动作在给定的初始延迟后首先启用,然后在给定的时间段内启用;也就是说,执行将在initialDelay之后开始,然后是initialDelay+period,然后是initialDelay+2*period,依此类推。如果任务的任何执行遇到异常,则会抑制后续执行。否则,任务将仅通过取消或终止执行人而终止。如果此任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会同时执行。

代码示例

代码示例来源:origin: code4craft/webmagic

private void initFlushThread() {
  flushThreadPool = Executors.newScheduledThreadPool(1);
  flushThreadPool.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      flush();
    }
  }, 10, 10, TimeUnit.SECONDS);
}

代码示例来源:origin: shuzheng/zheng

private void scheduleClockUpdating() {
  ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable runnable) {
      Thread thread = new Thread(runnable, "System Clock");
      thread.setDaemon(true);
      return thread;
    }
  });
  scheduler.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      now.set(System.currentTimeMillis());
    }
  }, period, period, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: alibaba/jstorm

public void register(TimeUnit timeUnit) {
  future = threadPool.scheduleAtFixedRate(this, firstTime, frequency, timeUnit);
  LOG.info("Successfully register timer " + this);
}

代码示例来源:origin: alipay/sofa-rpc

public ConsulManager(String host, int port) {
  client = new ConsulClient(host, port);
  ttlScheduler = new TtlScheduler(client);
  scheduleRegistry = Executors.newScheduledThreadPool(1, new NamedThreadFactory("retryFailedTtl", true));
  scheduleRegistry.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      try {
        retryFailedTtl();
      } catch (Throwable e) {
        if (LOGGER.isInfoEnabled()) {
          LOGGER.info("retry registry znode failed", e);
        }
      }
    }
  }, ConsulConstants.HEARTBEAT_CIRCLE, ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
  if (LOGGER.isInfoEnabled()) {
    LOGGER.info("ConsulEcwidClient init finish. client host:" + host + ", port:" + port);
  }
}

代码示例来源:origin: qunarcorp/qmq

private CachedOfflineStateManager() {
  refresh();
  scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("meta-info-offlinestate-refresh-%d").build());
  scheduledExecutor.scheduleAtFixedRate(this::refresh, REFRESH_PERIOD_SECONDS, REFRESH_PERIOD_SECONDS, TimeUnit.SECONDS);
  log.info("CachedOfflineStateManager started");
}

代码示例来源:origin: linkedin/kafka-monitor

@Override
public synchronized void start() {
 _executor.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
   try {
    reportMetrics();
   } catch (Exception e) {
    LOG.error(_name + "/KafkaMetricsReporterService failed to report metrics", e);
   }
  }
 }, _reportIntervalSec, _reportIntervalSec, TimeUnit.SECONDS);
 LOG.info("{}/KafkaMetricsReporterService started", _name);
}

代码示例来源:origin: alipay/sofa-rpc

public ConsulManager(String host, int port) {
  client = new ConsulClient(host, port);
  ttlScheduler = new TtlScheduler(client);
  scheduleRegistry = Executors.newScheduledThreadPool(1, new NamedThreadFactory("retryFailedTtl", true));
  scheduleRegistry.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      try {
        retryFailedTtl();
      } catch (Throwable e) {
        if (LOGGER.isInfoEnabled()) {
          LOGGER.info("retry registry znode failed", e);
        }
      }
    }
  }, ConsulConstants.HEARTBEAT_CIRCLE, ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
  if (LOGGER.isInfoEnabled()) {
    LOGGER.info("ConsulEcwidClient init finish. client host:" + host + ", port:" + port);
  }
}

代码示例来源:origin: Netflix/conductor

@Inject
public EventProcessor(ExecutionService executionService, MetadataService metadataService,
           ActionProcessor actionProcessor, EventQueues eventQueues, JsonUtils jsonUtils, Configuration config) {
  this.executionService = executionService;
  this.metadataService = metadataService;
  this.actionProcessor = actionProcessor;
  this.eventQueues = eventQueues;
  this.jsonUtils = jsonUtils;
  int executorThreadCount = config.getIntProperty("workflow.event.processor.thread.count", 2);
  if (executorThreadCount > 0) {
    executorService = Executors.newFixedThreadPool(executorThreadCount);
    refresh();
    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::refresh, 60, 60, TimeUnit.SECONDS);
    logger.info("Event Processing is ENABLED. executorThreadCount set to {}", executorThreadCount);
  } else {
    logger.warn("Event processing is DISABLED. executorThreadCount set to {}", executorThreadCount);
  }
}

代码示例来源:origin: stackoverflow.com

@WebListener
public class BackgroundJobManager implements ServletContextListener {

  private ScheduledExecutorService scheduler;

  @Override
  public void contextInitialized(ServletContextEvent event) {
    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS);
    scheduler.scheduleAtFixedRate(new SomeHourlyJob(), 0, 1, TimeUnit.HOURS);
    scheduler.scheduleAtFixedRate(new SomeQuarterlyJob(), 0, 15, TimeUnit.MINUTES);
  }

  @Override
  public void contextDestroyed(ServletContextEvent event) {
    scheduler.shutdownNow();
  }

}

代码示例来源:origin: pinterest/secor

private static void loop(ProgressMonitor progressMonitor, long interval) {
final ProgressMonitor monitor = progressMonitor;
Runnable runner = new Runnable() {
  public void run() {
    try {
    monitor.exportStats();
    } catch (Throwable t) {
    LOG.error("Progress monitor failed", t);
    }
  }
  };
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(runner, 0, interval, TimeUnit.SECONDS);
}

代码示例来源:origin: springside/springside4

/**
 * 启动定时任务.
 */
public void start(long period, TimeUnit unit) {
  if (started) {
    throw new IllegalStateException("Scheduler had been started before");
  }
  executor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      try {
        report();
      } catch (Throwable e) {
        logger.error(e.getMessage(), e);
      }
    }
  }, period, period, unit);
  started = true;
  logger.info("metric reporters started.");
}

代码示例来源:origin: apache/drill

@Override
public void start(HiveConf hiveConf) throws Exception {
 this.hiveConf = hiveConf;
 HiveTxnManager mgr = TxnManagerFactory.getTxnManagerFactory().getTxnManager(hiveConf);
 if(!mgr.supportsAcid()) {
  LOG.info(this.getClass().getName() + " not started since " +
   mgr.getClass().getName()  + " does not support Acid.");
  return;//there are no transactions in this case
 }
 pool = Executors.newScheduledThreadPool(1, new ThreadFactory() {
  private final AtomicInteger threadCounter = new AtomicInteger();
  @Override
  public Thread newThread(Runnable r) {
   return new Thread(r, HouseKeeperServiceBase.this.getClass().getName() + "-" + threadCounter.getAndIncrement());
  }
 });
 TimeUnit tu = TimeUnit.MILLISECONDS;
 pool.scheduleAtFixedRate(getScheduedAction(hiveConf, isAliveCounter), getStartDelayMs(),
  getIntervalMs(), tu);
 LOG.info("Started " + this.getClass().getName() + " with delay/interval = " + getStartDelayMs() + "/" +
  getIntervalMs() + " " + tu);
}

代码示例来源:origin: apache/shiro

protected void startReloadThread() {
  if (this.reloadIntervalSeconds > 0) {
    this.scheduler = Executors.newSingleThreadScheduledExecutor();
    ((ScheduledExecutorService) this.scheduler).scheduleAtFixedRate(this, reloadIntervalSeconds, reloadIntervalSeconds, TimeUnit.SECONDS);
  }
}

代码示例来源:origin: ReactiveX/RxJava

static void tryStart(boolean purgeEnabled) {
  if (purgeEnabled) {
    for (;;) {
      ScheduledExecutorService curr = PURGE_THREAD.get();
      if (curr != null) {
        return;
      }
      ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge"));
      if (PURGE_THREAD.compareAndSet(curr, next)) {
        next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS);
        return;
      } else {
        next.shutdownNow();
      }
    }
  }
}

代码示例来源:origin: linkedin/kafka-monitor

@Override
public synchronized void start() {
 _executor.scheduleAtFixedRate(
  new Runnable() {
   @Override
   public void run() {
    try {
     reportMetrics();
    } catch (Exception e) {
     LOG.error(_name + "/StatsdMetricsReporterService failed to report metrics", e);
    }
   }
  }, _reportIntervalSec, _reportIntervalSec, TimeUnit.SECONDS
 );
 LOG.info("{}/StatsdMetricsReporterService started", _name);
}

代码示例来源:origin: apache/kylin

@SuppressWarnings("rawtypes")
@Ignore("why test JDK feature?")
@Test
public void testSchedulerPool() throws InterruptedException {
  logger.info("testSchedulerPool");
  ScheduledExecutorService fetchPool = Executors.newScheduledThreadPool(1);
  final CountDownLatch countDownLatch = new CountDownLatch(3);
  ScheduledFuture future = fetchPool.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      countDownLatch.countDown();
    }
  }, 0, 1, TimeUnit.SECONDS);
  assertTrue("countDownLatch should reach zero in 15 secs", countDownLatch.await(7, TimeUnit.SECONDS));
  assertTrue("future should still running", future.cancel(true));
  final CountDownLatch countDownLatch2 = new CountDownLatch(3);
  ScheduledFuture future2 = fetchPool.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      countDownLatch2.countDown();
      throw new RuntimeException();
    }
  }, 0, 1, TimeUnit.SECONDS);
  assertFalse("countDownLatch2 should NOT reach zero in 15 secs", countDownLatch2.await(7, TimeUnit.SECONDS));
  assertFalse("future2 should has been stopped", future2.cancel(true));
}

代码示例来源:origin: stackoverflow.com

private ScheduledExecutorService scheduler;

public void contextInitialized(ServletContextEvent event) {
  scheduler = Executors.newSingleThreadScheduledExecutor();
  scheduler.scheduleAtFixedRate(new CleanDBTask(), 0, 1, TimeUnit.HOURS);
  scheduler.scheduleAtFixedRate(new StatisticsTask(), 0, 15, TimeUnit.MINUTES);
}

public void contextDestroyed(ServletContextEvent event) {
  scheduler.shutdownNow();
}

代码示例来源:origin: apache/storm

public LocalClient(LocalServer server) {
  _server = server;
  _pendingDueToUnregisteredServer = new LinkedBlockingQueue<>();
  _pendingFlusher = Executors.newScheduledThreadPool(1, new ThreadFactory() {
    @Override
    public Thread newThread(Runnable runnable) {
      Thread thread = new Thread(runnable);
      thread.setName("LocalClientFlusher-" + thread.getId());
      thread.setDaemon(true);
      return thread;
    }
  });
  _pendingFlusher.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      try {
        //Ensure messages are flushed even if no more sends are performed
        flushPending();
      } catch (Throwable t) {
        LOG.error("Uncaught throwable in pending message flusher thread, messages may be lost", t);
        throw new RuntimeException(t);
      }
    }
  }, 5, 5, TimeUnit.SECONDS);
}

代码示例来源:origin: linkedin/kafka-monitor

@Override
public synchronized void start() {
 _executor.scheduleAtFixedRate(
  new Runnable() {
   @Override
   public void run() {
    try {
     reportMetrics();
    } catch (Exception e) {
     LOG.error(_name + "/DefaultMetricsReporterService failed to report metrics", e);
    }
   }
  }, _reportIntervalSec, _reportIntervalSec, TimeUnit.SECONDS
 );
 LOG.info("{}/DefaultMetricsReporterService started", _name);
}

代码示例来源:origin: stackoverflow.com

@WebListener
public class BackgroundJobManager implements ServletContextListener {

  private ScheduledExecutorService scheduler;

  @Override
  public void contextInitialized(ServletContextEvent event) {
    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new YourParsingJob(), 0, 5, TimeUnit.HOUR);
  }

  @Override
  public void contextDestroyed(ServletContextEvent event) {
    scheduler.shutdownNow();
  }

}

相关文章