@Bean public ScheduledFuture<List<String>> createBuckets(MinioClient minioClient, ScheduledExecutorService executorService, S3ClientProperties clientProps) { return executorService.schedule(() -> { try { for (String bucket : clientProps.buckets) { logger.info("Checking bucket: {}", bucket); if (minioClient.bucketExists(bucket)) continue; logger.info("Bucket doesn't exist, creating one"); minioClient.makeBucket(bucket); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { logger.info("Bucket successfully created"); } return clientProps.buckets; }, 5, TimeUnit.SECONDS); }
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) { ScheduledFuture scheduledFuture = null; try { TaskDefine taskDefine = resolveTaskName(task); if (taskDefine.getType().equals(TaskDefine.TYPE_SPRING_TASK)) { super.scheduleWithFixedDelay(task, startTime, delay); LOGGER.debug(":添加本地任务[" + taskDefine.stringKey() + "]"); } else { taskDefine.setStartTime(startTime); taskDefine.setPeriod(delay); scheduleTask.addTask(taskDefine); scheduledFuture = super.scheduleWithFixedDelay(taskWrapper(task), startTime, delay); LOGGER.debug(currenScheduleServer.getUuid() + ":自动向集群注册任务[" + taskDefine.stringKey() + "]"); } } catch (Exception e) { LOGGER.error("update task error", e); } return scheduledFuture; }
public final void applyEnergyBuff(final MapleCharacter applyto, final boolean infinity, int targets) { final long starttime = System.currentTimeMillis(); if (infinity) { applyto.getClient().getSession().write(BuffPacket.giveEnergyChargeTest(0, info.get(MapleStatInfo.time) / 1000, targets)); applyto.registerEffect(this, starttime, null, applyto.getId()); } else { final EnumMap<CharacterTemporaryStat, Integer> stat = new EnumMap<>(CharacterTemporaryStat.class); stat.put(CharacterTemporaryStat.EnergyCharged, 10000); applyto.cancelEffect(this, true, -1, stat); applyto.getMap().broadcastMessage(applyto, BuffPacket.giveEnergyChargeTest(applyto.getId(), 10000, info.get(MapleStatInfo.time) / 1000), false); final CancelEffectAction cancelAction = new CancelEffectAction(applyto, this, starttime, stat); final ScheduledFuture<?> schedule = BuffTimer.getInstance().schedule(cancelAction, ((starttime + info.get(MapleStatInfo.time)) - System.currentTimeMillis())); applyto.registerEffect(this, starttime, schedule, stat, false, info.get(MapleStatInfo.time), applyto.getId()); } }
public static void main(String[] args) { final LoadMonitor monitor = new LoadMonitor(null); final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> monitorTask = monitor.startMonitoring(scheduler); final ScheduledFuture<?> printTask = monitor.printMonitoring(scheduler); // Run the tasks for 2 minutes scheduler.schedule( new Runnable() { public void run() { monitorTask.cancel(true); printTask.cancel(true); } }, 5*60, TimeUnit.SECONDS); }
@Test public void testScheduleWithDelay() throws ExecutionException, InterruptedException { MockRunLoop runLoop = new MockRunLoop(); try { assertEquals(0, runLoop.getThreadPool().getCorePoolSize()); ScheduledFuture future = runLoop.schedule(new Runnable() { @Override public void run() { } }, 500L); assertEquals(1, runLoop.getThreadPool().getCorePoolSize()); future.get(); assertTrue(runLoop.errors.isEmpty()); } finally { runLoop.getExecutorService().shutdownNow(); } }
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) { ScheduledFuture scheduledFuture = null; try { TaskDefine taskDefine = resolveTaskName(task); if (taskDefine.getType().equals(TaskDefine.TYPE_SPRING_TASK)) { super.scheduleAtFixedRate(task, period); LOGGER.debug(":添加本地任务[" + taskDefine.stringKey() + "]"); } else { taskDefine.setPeriod(period); scheduleTask.addTask(taskDefine); scheduledFuture = super.scheduleAtFixedRate(taskWrapper(task), period); LOGGER.debug(currenScheduleServer.getUuid() + ":自动向集群注册任务[" + taskDefine.stringKey() + "]"); } } catch (Exception e) { LOGGER.error("update task error", e); } return scheduledFuture; }
public static void a() { try { for (WeakReference weakReference : a) { ScheduledFuture scheduledFuture = (ScheduledFuture) weakReference.get(); if (scheduledFuture != null) { scheduledFuture.cancel(false); } } a.clear(); if (!b.isShutdown()) { b.shutdown(); } if (!d.isShutdown()) { d.shutdown(); } b.awaitTermination(c, TimeUnit.SECONDS); d.awaitTermination(c, TimeUnit.SECONDS); } catch (Exception e) { } }
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) { if (!enabled) { logger.debug("skip : {}", task); return null; } ScheduledFuture<?> future = instance.scheduleAtFixedRate(task, startTime, period); String runnableKey = findRunnableKey(task); if (Boolean.FALSE.equals(skipMap.get(runnableKey))) { future.cancel(true); } return future; }
@Override public void dispose () { ScheduledFuture<?> job; synchronized ( this ) { job = this.job; this.job = null; } if ( job != null ) { logger.debug ( "Cancelling reload job" ); job.cancel ( true ); } }
public void silentApplyBuff(MapleCharacter chr, long starttime) { int localDuration = duration; localDuration = alchemistModifyVal(chr, localDuration, false); CancelEffectAction cancelAction = new CancelEffectAction(chr, this, starttime); ScheduledFuture<?> schedule = TimerManager.getInstance().schedule(cancelAction, ((starttime + localDuration) - System.currentTimeMillis())); chr.registerEffect(this, starttime, schedule); SummonMovementType summonMovementType = getSummonMovementType(); if (summonMovementType != null) { final MapleSummon tosummon = new MapleSummon(chr, sourceid, chr.getPosition(), summonMovementType); if (!tosummon.isStationary()) { chr.addSummon(sourceid, tosummon); tosummon.addHP(x); } } if (sourceid == Corsair.BATTLE_SHIP) { chr.announce(MaplePacketCreator.skillCooldown(5221999, chr.getBattleshipHp())); } }
/** * Start streaming the items specified in the subscription. * * @param subscription Items to stream to client */ public void start(Subscription subscription) { if (scheduler != null) { return; } logger.info("Sending graph data to {}:{}", subscription.client(), port); socketAddress = new InetSocketAddress(subscription.client(), port); scheduler = Executors.newSingleThreadScheduledExecutor(); // FIXME: future not checked for exception ScheduledFuture<?> future = scheduler.scheduleAtFixedRate( () -> { Buffer buffer = new Buffer(); try { subscription.measurementsToJson(buffer); byte[] bytes = buffer.readByteArray(); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, socketAddress); socket.send(packet); } catch (IOException e) { logger.error("Exception sending grapher data", e); } }, 0, 5, MILLISECONDS); }
/** * scheduleAtFixedRate executes runnable after given initial delay */ public void testSchedule4() throws Exception { final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final long startTime = System.nanoTime(); final CountDownLatch done = new CountDownLatch(1); Runnable task = new CheckedRunnable() { public void realRun() { done.countDown(); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); }}; ScheduledFuture f = p.scheduleAtFixedRate(task, timeoutMillis(), LONG_DELAY_MS, MILLISECONDS); await(done); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); f.cancel(true); } }
/** * getQueue returns the work queue, which contains queued tasks */ public void testGetQueue() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p, done)) { final CountDownLatch threadStarted = new CountDownLatch(1); ScheduledFuture[] tasks = new ScheduledFuture[5]; for (int i = 0; i < tasks.length; i++) { Runnable r = new CheckedRunnable() { public void realRun() throws InterruptedException { threadStarted.countDown(); await(done); }}; tasks[i] = p.schedule(r, 1, MILLISECONDS); } await(threadStarted); BlockingQueue<Runnable> q = p.getQueue(); assertTrue(q.contains(tasks[tasks.length - 1])); assertFalse(q.contains(tasks[0])); } }
/** * Removes the given {@code scanner} from the collection of this network's scanners. * This method has no effect if the given {@code scanner} does not exist in the collection of this network's scanners. * * @param scanner the scanner to remove * @return true, if successfully removed */ public boolean removeScanner(final Scanner scanner) { final ScheduledFuture<?> scheduled_scanner; final boolean removable; synchronized (scheduled_scanners) { removable = isAdded(scanner); scheduled_scanner = removable ? scheduled_scanners.remove(scanner) : null; } if (scheduled_scanner != null) { scheduled_scanner.cancel(true); } if (removable) { scanner.removeEnabledPropertyChangeListener(enabled_change_listener); } return removable; }
/** * Method that schedule in the executor a periodic tasks. It calls the method of its parent class using * the super keyword and stores the period of the task. */ @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { ScheduledFuture<?> task= super.scheduleAtFixedRate(command, initialDelay, period, unit); MyScheduledTask<?> myTask=(MyScheduledTask<?>)task; myTask.setPeriod(TimeUnit.MILLISECONDS.convert(period,unit)); return task; }
public ScheduledFuture<?> schedule() { synchronized (this.triggerContextMonitor) { this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext); if (this.scheduledExecutionTime == null) { return null; } long initialDelay = this.scheduledExecutionTime.getTime() - System.currentTimeMillis(); this.currentFuture = this.executor.schedule(this, initialDelay, TimeUnit.MILLISECONDS); return this; } }
private void cleanUpKeepAliveTimes(String deviceName) { ScheduledFuture<?> future = deviceKeepAliveTimers.get(deviceName); if (future != null) { future.cancel(true); deviceKeepAliveTimers.remove(deviceName); } }
private void scheduleDeviceKeepAliveTimer(DeviceData dd) { ScheduledFuture<?> f = scheduler.schedule( () -> { log.warn("[{}] Device is going to be disconnected because of timeout! timeout = {} milliseconds", dd.getName(), dd.getTimeout()); deviceKeepAliveTimers.remove(dd.getName()); gateway.onDeviceDisconnect(dd.getName()); }, dd.getTimeout(), TimeUnit.MILLISECONDS ); deviceKeepAliveTimers.put(dd.getName(), f); }
public void testNoOpScheduledExecutor() throws InterruptedException { taskDone = false; Runnable task = new Runnable() { @Override public void run() { taskDone = true; } }; ScheduledFuture<?> future = TestingExecutors.noOpScheduledExecutor().schedule( task, 10, TimeUnit.MILLISECONDS); Thread.sleep(20); assertFalse(taskDone); assertFalse(future.isDone()); }
@Override public CompletableFuture<MarginCalcResult> calculateAsync(Ccp ccp, MarginCalcRequest request) { CompletableFuture<MarginCalcResult> resultPromise = new CompletableFuture<>(); Runnable r = () -> { String calcId = createCalculation(ccp, request); Instant timeout = Instant.now().plus(POLL_TIMEOUT); Runnable pollTask = () -> { MarginCalcResult calcResult = getCalculation(ccp, calcId); if (calcResult.getStatus() == MarginCalcResultStatus.COMPLETED) { resultPromise.complete(calcResult); return; } if (Instant.now().isAfter(timeout)) { resultPromise.completeExceptionally(new MarginException("Timed out while polling margin service", "Time Out")); return; } }; ScheduledFuture<?> scheduledTask = invoker.getExecutor().scheduleWithFixedDelay(pollTask, POLL_WAIT, POLL_WAIT, TimeUnit.MILLISECONDS); resultPromise.whenComplete((res, ex) -> { scheduledTask.cancel(true); // cleanup server state quietly try { deleteCalculation(ccp, calcId); } catch (RuntimeException ex2) { // ignore } }); }; invoker.getExecutor().execute(r); return resultPromise; }
@Override public ListenableScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit); return new ListenableScheduledTask<Void>(task, scheduled); }
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return null; }
private void stopHeartbeatTimer() { try { ScheduledFuture<?> timer = heatbeatTimer; if (timer != null && ! timer.isCancelled()) { timer.cancel(true); } } catch (Throwable t) { logger.warn(t.getMessage(), t); } finally { heatbeatTimer =null; } }
private void startCacheCleanerThreadIfNeeded() { if (cacheCleaner == null) { cacheCleaner = new CacheCleaner(); long rateMs = cacheCleaner.getRateInMs(); ScheduledFuture<?> future = cleanerExecutor.scheduleAtFixedRate(cacheCleaner, rateMs, rateMs, TimeUnit.MILLISECONDS); cacheCleaner.setFuture(future); if (LOG.isDebugEnabled()) { LOG.debug(this + ": starting cache cleaner thread which will run " + "every " + rateMs + " ms"); } } }
<T> ScheduledFuture<T> schedule(Callable<T> command, long delayMillis) { checkNotNull(command); try { return ensureScheduledExecutorService().schedule(command, delayMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // This may fail if the underlying ThreadFactory does not support long-lived threads. throw new UnsupportedOperationException("Scheduled tasks not supported", e); } }
public void questTimeLimit(final MapleQuest quest, int time) { ScheduledFuture<?> sf = TimerManager.getInstance().schedule(new Runnable() { @Override public void run() { announce(MaplePacketCreator.questExpire(quest.getId())); MapleQuestStatus newStatus = new MapleQuestStatus(quest, MapleQuestStatus.Status.NOT_STARTED); newStatus.setForfeited(getQuest(quest).getForfeited() + 1); updateQuest(newStatus); } }, time); announce(MaplePacketCreator.addQuestTimeLimit(quest.getId(), time)); timers.add(sf); }
/** * 启动动态定时任务 * 支持: * 1 cron时间表达式,立即执行 * 2 startTime + period,指定时间,定时进行 * 3 period,定时进行,立即开始 * 4 startTime,指定时间执行 * * @param targetBean 目标bean名称 * @param targetMethod 方法 * @param cronExpression cron表达式 * @param startTime 指定执行时间 * @param period 定时进行,立即开始 * @param params 给方法传递的参数 * @param extKeySuffix 任务后缀名 * @param onlyOne 备用字段 */ public static void scheduleTask(String targetBean, String targetMethod, String cronExpression, Date startTime, long period, String params, String extKeySuffix, boolean onlyOne) { String scheduleKey = ScheduleUtil.buildScheduleKey(targetBean, targetMethod, extKeySuffix); try { if (!SCHEDULE_FUTURES.containsKey(scheduleKey)) { ScheduledFuture<?> scheduledFuture = null; ScheduledMethodRunnable scheduledMethodRunnable = buildScheduledRunnable(targetBean, targetMethod, params, extKeySuffix, onlyOne); if (scheduledMethodRunnable != null) { if (StringUtils.isNotEmpty(cronExpression)) { Trigger trigger = new CronTrigger(cronExpression); scheduledFuture = ConsoleManager.getSchedulerTaskManager().schedule(scheduledMethodRunnable, trigger); } else if (startTime != null) { if (period > 0) { scheduledFuture = ConsoleManager.getSchedulerTaskManager().scheduleAtFixedRate(scheduledMethodRunnable, startTime, period); } else { scheduledFuture = ConsoleManager.getSchedulerTaskManager().schedule(scheduledMethodRunnable, startTime); } } else if (period > 0) { scheduledFuture = ConsoleManager.getSchedulerTaskManager().scheduleAtFixedRate(scheduledMethodRunnable, period); } if (null != scheduledFuture) { SCHEDULE_FUTURES.put(scheduleKey, scheduledFuture); LOGGER.debug("Building new schedule task, target bean " + targetBean + " target method " + targetMethod + "."); } } else { ConsoleManager.getSchedulerTaskManager().getScheduleTask() .saveRunningInfo(scheduleKey, ConsoleManager.getSchedulerTaskManager().getScheduleServerUUid(), "bean not exists"); LOGGER.debug("Bean name is not exists."); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
private void addTaskOrUpdateLastAccessTime(Object taskId, long refreshMillis, K key) { if (refreshMillis > 0 && taskId != null) { RefreshTask refreshTask = taskMap.computeIfAbsent(taskId, tid -> { RefreshTask task = new RefreshTask(taskId, key); task.lastAccessTime = System.currentTimeMillis(); ScheduledFuture<?> future = JetCacheExecutor.heavyIOExecutor().scheduleWithFixedDelay( task, refreshMillis, refreshMillis, TimeUnit.MILLISECONDS); task.future = future; return task; }); refreshTask.lastAccessTime = System.currentTimeMillis(); } }
@Override public void onInstanceDestroy(Instance instance) { // Stop running spawn task final ScheduledFuture<?> task = instance.getParameters().getObject("spawnTask", ScheduledFuture.class); if ((task != null) && !task.isDone()) { task.cancel(true); } instance.setParameter("spawnTask", null); }
private static void startScheduledThreads() { //Schedule update notifier thread ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(new UpdateNotifier(username, repoName, version_number), 0, 96, TimeUnit.HOURS); }
@Override public <T> ScheduledFuture<T> submit(Callable<T> task) { if (task == null) throw new NullPointerException(); ScheduledFutureImpl<T> future = newTaskFor(task); execute(future); return future; }
@OnOpen public void onOpen(final Session session, @PathParam("id") String id) { session.setMaxIdleTimeout(0); SimulationModel model = simStore.get(UUID.fromString(id)); Simulation sim = model.getSimulation(); SimulationWrapper wrapper = (SimulationWrapper) model.getWrapper(sim); Runnable sendConfigurationUpdate = () -> { if(sim.getController().isPaused() || !sim.getController().isActive()) { return; } sim.getController().doActionNow(() -> { Boundary[] boundaries = new Boundary[sim.getBoxCount()]; for (int i = 0; i < sim.getBoxCount(); i++) { boundaries[i] = sim.getBox(i).getBoundary(); } ConfigurationUpdate update = new ConfigurationUpdate( wrapper.getAllCoordinates(), boundaries ); session.getAsyncRemote().sendObject(update); }); }; ScheduledFuture<?> task = executor.scheduleWithFixedDelay(sendConfigurationUpdate, 0, 33, TimeUnit.MILLISECONDS); session.getUserProperties().put("task", task); }
public void registerEffect(MapleStatEffect effect, long starttime, ScheduledFuture<?> schedule) { if (effect.isDragonBlood()) { prepareDragonBlood(effect); } else if (effect.isBerserk()) { checkBerserk(); } else if (effect.isBeholder()) { final int beholder = DarkKnight.BEHOLDER; if (beholderHealingSchedule != null) { beholderHealingSchedule.cancel(false); } if (beholderBuffSchedule != null) { beholderBuffSchedule.cancel(false); } Skill bHealing = SkillFactory.getSkill(DarkKnight.AURA_OF_BEHOLDER); int bHealingLvl = getSkillLevel(bHealing); if (bHealingLvl > 0) { final MapleStatEffect healEffect = bHealing.getEffect(bHealingLvl); int healInterval = healEffect.getX() * 1000; beholderHealingSchedule = TimerManager.getInstance().register(new Runnable() { @Override public void run() { addHP(healEffect.getHp()); client.announce(MaplePacketCreator.showOwnBuffEffect(beholder, 2)); getMap().broadcastMessage(MapleCharacter.this, MaplePacketCreator.summonSkill(getId(), beholder, 5), true); getMap().broadcastMessage(MapleCharacter.this, MaplePacketCreator.showOwnBuffEffect(beholder, 2), false); } }, healInterval, healInterval); } Skill bBuff = SkillFactory.getSkill(DarkKnight.HEX_OF_BEHOLDER); if (getSkillLevel(bBuff) > 0) { final MapleStatEffect buffEffect = bBuff.getEffect(getSkillLevel(bBuff)); int buffInterval = buffEffect.getX() * 1000; beholderBuffSchedule = TimerManager.getInstance().register(new Runnable() {
@Test public void testCancel() throws InterruptedException, ExecutionException { RScheduledExecutorService executor = redisson.getExecutorService("test"); ScheduledFuture<?> future1 = executor.schedule(new ScheduledRunnableTask("executed1"), 1, TimeUnit.SECONDS); cancel(future1); Thread.sleep(2000); assertThat(redisson.getAtomicLong("executed1").isExists()).isFalse(); }
/** * Primarily used to terminate the Festival Manager, when the Seven Signs period changes. * * @return ScheduledFuture festManagerScheduler */ @SuppressWarnings("rawtypes") protected final ScheduledFuture getFestivalManagerSchedule() { if (_managerScheduledTask == null) startFestivalManager(); return _managerScheduledTask; }
/** * Starts the hello timer which sends hello packet every configured seconds. * * @param channel netty channel instance */ public void startHelloSender(Channel channel) { log.debug("IsisInterfaceImpl::startHelloSender"); if (!helloSenderStarted) { isisHelloPduSender = new IsisHelloPduSender(channel, this); exServiceHello = Executors.newSingleThreadScheduledExecutor(); final ScheduledFuture<?> helloHandle = exServiceHello.scheduleAtFixedRate(isisHelloPduSender, 0, helloInterval, TimeUnit.SECONDS); helloSenderStarted = true; } }
public ScheduledFuture<?> printMonitoring(ScheduledExecutorService ses) { final LoadMonitor mon = this; ScheduledFuture<?> monitorTask = ses.scheduleAtFixedRate( new Runnable() { public void run() { System.out.println(mon.getLoad()); } }, LOADMONITOR_SAMPLING_INTERVAL/2, LOADMONITOR_SAMPLING_INTERVAL, TimeUnit.MILLISECONDS); return monitorTask; }
public ScheduledFuture<?> schedule() { this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext); if (this.scheduledExecutionTime == null) { return null; } setTimer(getTimerManager().schedule(this, this.scheduledExecutionTime)); return this; }
@SuppressWarnings("rawtypes") public ScheduledFuture scheduleAiAtFixedRate(Runnable r, long initial, long delay) { try { if (delay < 0) delay = 0; if (initial < 0) initial = 0; return _aiScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ } }
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { if (ses == null) ses = Executors.newScheduledThreadPool(1); try { return ses.schedule(command, delay, unit); } catch (Exception e) { return new MockFuture<Object>(new ExecutionException(e)); } }