本文整理汇总了Java中java.util.concurrent.ScheduledThreadPoolExecutor类的典型用法代码示例。如果您正苦于以下问题:Java ScheduledThreadPoolExecutor类的具体用法?Java ScheduledThreadPoolExecutor怎么用?Java ScheduledThreadPoolExecutor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ScheduledThreadPoolExecutor类属于java.util.concurrent包,在下文中一共展示了ScheduledThreadPoolExecutor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testTimedInvokeAll4
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
/**
* get of element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() throws Exception {
final ExecutorService e = new ScheduledThreadPoolExecutor(2);
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<>();
l.add(new NPETask());
List<Future<String>> futures =
e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
assertEquals(1, futures.size());
try {
futures.get(0).get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
示例2: RuntimeUtil
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
private RuntimeUtil() {
scheduler = new ScheduledThreadPoolExecutor(
schedulerThreads,
new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger(0);
public Thread newThread(Runnable runnable) {
try {
return AccessController.doPrivileged(
new NewThreadAction(runnable,
"Scheduler(" + count.getAndIncrement() + ")",
true));
} catch (Throwable t) {
runtimeLog.log(Level.WARNING,
"scheduler thread factory throws", t);
return null;
}
}
});
/*
* We would like to allow the scheduler's threads to terminate
* if possible, but a bug in DelayQueue.poll can cause code
* like this to result in a busy loop:
*/
// stpe.setKeepAliveTime(10, TimeUnit.MINUTES);
// stpe.allowCoreThreadTimeOut(true);
}
示例3: start
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public void start() {
bootstrap.group(group).channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// ch.pipeline().addLast(new IdleStateHandler(1, 1, 5));
ch.pipeline().addLast(new KyroMsgDecoder());
ch.pipeline().addLast(new KyroMsgEncoder());
ch.pipeline().addLast(new ClientHandler());
}
});
new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
scanResponseTable(3000);
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
}
示例4: main
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
final Configuration conf = HBaseConfiguration.create();
final ChoreService choreService = new ChoreService("CANARY_TOOL");
final ScheduledChore authChore = AuthUtil.getAuthChore(conf);
if (authChore != null) {
choreService.scheduleChore(authChore);
}
// loading the generic options to conf
new GenericOptionsParser(conf, args);
int numThreads = conf.getInt("hbase.canary.threads.num", MAX_THREADS_NUM);
LOG.info("Number of exection threads " + numThreads);
ExecutorService executor = new ScheduledThreadPoolExecutor(numThreads);
Class<? extends Sink> sinkClass =
conf.getClass("hbase.canary.sink.class", RegionServerStdOutSink.class, Sink.class);
Sink sink = ReflectionUtils.newInstance(sinkClass);
int exitCode = ToolRunner.run(conf, new Canary(executor, sink), args);
choreService.shutdown();
executor.shutdown();
System.exit(exitCode);
}
示例5: main
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public static void main(String[] args)
{
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(
10);
Runnable event = new Runnable()
{
@Override
public void run()
{
System.out.println("吃饭,睡觉,打豆豆");
}
};
scheduler.schedule(event, 1, TimeUnit.SECONDS);
scheduler.scheduleAtFixedRate(event, 5, 1, TimeUnit.SECONDS);
}
示例6: init
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
@PostConstruct
public void init() {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("SendNodeServerInfo-schedule-pool-%d").daemon(true).build());
scheduledExecutorService.scheduleAtFixedRate(() ->
{
//将负载加载到ZK中
if (!CollectionUtils.isEmpty(dataCenterChannelStore.getAllChannels())) {
dataCenterChannelStore.getAllChannels().stream().forEach(e -> {
log.info("channel id:{}, {}", e.id(), e);
});
}
applicationEventPublisher.publishEvent(
NodeServerInfoEvent.builder()
.name(goPushNodeServerConfig.getName())
.nodeServerInfo(watch())
.build());
// 写入zk 其实不需要发送 NodeInfoReq
nodeSender.send(NodeInfoReq.builder().build());
}
, delay, delay, TimeUnit.MILLISECONDS);
}
示例7: start
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public void start() {
if (ses != null && !ses.isShutdown() && !ses.isTerminated()) {
return;
}
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(4, new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("TimerManager-Worker-" + threadNumber.getAndIncrement());
return t;
}
});
//this is a no-no, it actually does nothing..then why the fuck are you doing it?
stpe.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ses = stpe;
}
示例8: testListeningDecorator_scheduleSuccess
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public void testListeningDecorator_scheduleSuccess() throws Exception {
final CountDownLatch completed = new CountDownLatch(1);
ScheduledThreadPoolExecutor delegate = new ScheduledThreadPoolExecutor(1) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
completed.countDown();
}
};
ListeningScheduledExecutorService service = listeningDecorator(delegate);
ListenableFuture<Integer> future =
service.schedule(Callables.returning(42), 1, TimeUnit.MILLISECONDS);
/*
* Wait not just until the Future's value is set (as in future.get()) but
* also until ListeningScheduledExecutorService's wrapper task is done
* executing listeners, as detected by yielding control to afterExecute.
*/
completed.await();
assertTrue(future.isDone());
assertThat(future.get()).isEqualTo(42);
assertListenerRunImmediately(future);
assertEquals(0, delegate.getQueue().size());
}
示例9: afterPropertiesSet
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
public void afterPropertiesSet() throws Exception {
scheduler = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("Otter-Statistics-Table"),
new ThreadPoolExecutor.CallerRunsPolicy());
if (statUnit > 0) {
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
flushBehaviorHistory();
} catch (Exception e) {
logger.error("flush delay stat failed!", e);
}
}
}, statUnit, statUnit, TimeUnit.MILLISECONDS);
}
}
示例10: ChoreService
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
/**
* @param coreThreadPoolPrefix Prefix that will be applied to the Thread name of all threads
* spawned by this service
* @param corePoolSize The initial size to set the core pool of the ScheduledThreadPoolExecutor
* to during initialization. The default size is 1, but specifying a larger size may be
* beneficial if you know that 1 thread will not be enough.
*/
public ChoreService(final String coreThreadPoolPrefix, int corePoolSize, boolean jitter) {
this.coreThreadPoolPrefix = coreThreadPoolPrefix;
if (corePoolSize < MIN_CORE_POOL_SIZE) {
corePoolSize = MIN_CORE_POOL_SIZE;
}
final ThreadFactory threadFactory = new ChoreServiceThreadFactory(coreThreadPoolPrefix);
if (jitter) {
scheduler = new JitterScheduledThreadPoolExecutorImpl(corePoolSize, threadFactory, 0.1);
} else {
scheduler = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
scheduler.setRemoveOnCancelPolicy(true);
scheduledChores = new HashMap<ScheduledChore, ScheduledFuture<?>>();
choresMissingStartTime = new HashMap<ScheduledChore, Boolean>();
}
示例11: testPurge
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
/**
* purge eventually removes cancelled tasks from the queue
*/
public void testPurge() throws InterruptedException {
final ScheduledFuture[] tasks = new ScheduledFuture[5];
final Runnable releaser = new Runnable() { public void run() {
for (ScheduledFuture task : tasks)
if (task != null) task.cancel(true); }};
final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
try (PoolCleaner cleaner = cleaner(p, releaser)) {
for (int i = 0; i < tasks.length; i++)
tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
LONG_DELAY_MS, MILLISECONDS);
int max = tasks.length;
if (tasks[4].cancel(true)) --max;
if (tasks[3].cancel(true)) --max;
// There must eventually be an interference-free point at
// which purge will not fail. (At worst, when queue is empty.)
long startTime = System.nanoTime();
do {
p.purge();
long count = p.getTaskCount();
if (count == max)
return;
} while (millisElapsedSince(startTime) < LONG_DELAY_MS);
fail("Purge failed to remove cancelled tasks");
}
}
示例12: testFixedRateSequence
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
/**
* scheduleAtFixedRate executes series of tasks at given rate.
* Eventually, it must hold that:
* cycles - 1 <= elapsedMillis/delay < cycles
*/
public void testFixedRateSequence() throws InterruptedException {
final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
try (PoolCleaner cleaner = cleaner(p)) {
for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
final long startTime = System.nanoTime();
final int cycles = 8;
final CountDownLatch done = new CountDownLatch(cycles);
final Runnable task = new CheckedRunnable() {
public void realRun() { done.countDown(); }};
final ScheduledFuture periodicTask =
p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
final int totalDelayMillis = (cycles - 1) * delay;
await(done, totalDelayMillis + LONG_DELAY_MS);
periodicTask.cancel(true);
final long elapsedMillis = millisElapsedSince(startTime);
assertTrue(elapsedMillis >= totalDelayMillis);
if (elapsedMillis <= cycles * delay)
return;
// else retry with longer delay
}
fail("unexpected execution rate");
}
}
示例13: ChatSDKAbstractConversationsFragmentChatSDKThreadPool
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
private ChatSDKAbstractConversationsFragmentChatSDKThreadPool(){
if (NUMBER_OF_CORES <= 0)
NUMBER_OF_CORES = 2;
// Creates a thread pool manager
threadPool = new ThreadPoolExecutor(
NUMBER_OF_CORES, // Initial pool size
NUMBER_OF_CORES, // Max pool size
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
workQueue);
scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(NUMBER_OF_CORES);
}
开发者ID:MobileDev418,项目名称:chat-sdk-android-push-firebase,代码行数:17,代码来源:ChatSDKAbstractConversationsFragment.java
示例14: scheduler
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
@Override
protected ScheduledExecutorService scheduler() {
if (this.scheduler == null) {
synchronized (this) {
if (this.scheduler == null) {
ThreadFactory timerFactory = new ThreadFactoryBuilder()
.setNameFormat("AsyncReporter-" + id + "-timer-%d")
.setDaemon(true)
.build();
ScheduledThreadPoolExecutor timerPool = new ScheduledThreadPoolExecutor(timerThreads, timerFactory);
timerPool.setRemoveOnCancelPolicy(true);
this.scheduler = timerPool;
return timerPool;
}
}
}
return scheduler;
}
示例15: scheduleAtTheEndOfTime
import java.util.concurrent.ScheduledThreadPoolExecutor; //导入依赖的package包/类
void scheduleAtTheEndOfTime(ScheduledThreadPoolExecutor pool,
Runnable r, int how) {
switch (how) {
case 0:
pool.schedule(r, Long.MAX_VALUE, MILLISECONDS);
break;
case 1:
pool.schedule(Executors.callable(r), Long.MAX_VALUE, DAYS);
break;
case 2:
pool.scheduleWithFixedDelay(r, Long.MAX_VALUE, 1000, NANOSECONDS);
break;
case 3:
pool.scheduleAtFixedRate(r, Long.MAX_VALUE, 1000, MILLISECONDS);
break;
default:
fail(String.valueOf(how));
}
}