@Override protected void startItem(PlayableItem playableItem, Object loadedItem) { // Communicating with the activity is only possible after the activity // is started // if we send an broadcast event to early the activity won't be up // because there is no known way to query the activity state // we are sending the command delayed DIDLObject.Property<URI> albumArtUriProperty = playableItem.getItem() == null ? null : playableItem.getItem().getFirstProperty(DIDLObject.Property.UPNP.ALBUM_ART_URI.class); albumArtUri = (albumArtUriProperty == null) ? null : albumArtUriProperty.getValue(); commandExecutionTimer = new Timer(); commandExecutionTimer.schedule(new TimerTask() { @Override public void run() { Intent intent = new Intent(); intent.setAction(BackgroundMusicBroadcastReceiver.ACTION_PLAY); getContext().sendBroadcast(intent); } }, 600L); }
public void timerOne() { timer.schedule(new TimerTask() { @Override public void run() { System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start)); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } }, 1000); }
public SpongeStats(MCMarketApi marketApi, PluginContainer plugin) { super(marketApi); Sponge.getEventManager().registerListeners(plugin, this); Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!Sponge.getPluginManager().isLoaded(plugin.getId())) { timer.cancel(); return; } Sponge.getScheduler().createTaskBuilder().execute(() -> runEventsSender()).submit(plugin); } }, 1000 * 10, 1000 * 60); }
public void put(MyElement<K, V> element) { if (elements.size() == maxElements) { K firstKey = elements.keySet().iterator().next(); elements.remove(firstKey); } K key = element.getKey(); elements.put(key, element); if (!isEternal) { if (lifeTimeMs != 0) { TimerTask lifeTimerTask = getTimerTask(key, lifeElement -> lifeElement.getCreationTime() + lifeTimeMs); timer.schedule(lifeTimerTask, lifeTimeMs); } if (idleTimeMs != 0) { TimerTask idleTimerTask = getTimerTask(key, idleElement -> idleElement.getLastAccessTime() + idleTimeMs); timer.schedule(idleTimerTask, idleTimeMs, idleTimeMs); } } }
public synchronized void submit(final RunnableFuture task, long delay) { getTimer().schedule(new TimerTask() { @Override public void run() { Thread t = new Thread(new Runnable() { @Override public void run() { submit(task); } }); t.setDaemon(daemon); t.start(); } }, delay); }
/** * Starts the Scheduler which submits our data every 30 minutes. */ private void startSubmitting() { final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!plugin.isEnabled()) { // Plugin was disabled timer.cancel(); return; } // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) Bukkit.getScheduler().runTask(plugin, new Runnable() { @Override public void run() { submitData(); } }); } }, 1000*60*5, 1000*60*30); // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! // WARNING: Just don't do it! }
/** * Start sending time events to listeners. * @param playerIndex Player index to send times for */ private void sendTimeUpdates(int playerIndex) { this.timeUpdateSender = new TimerTask() { long startTime = System.currentTimeMillis(); long moveTime = settings.getMoveTimeMillis(); long gameTime = times[playerIndex - 1]; @Override public void run() { long elapsed = System.currentTimeMillis() - startTime; gameTime -= elapsed; moveTime -= elapsed; // Broadcast the elapsed times since the last TimerTask if(settings.gameTimingEnabled()) { listeners.forEach(listener -> listener.gameTimeChanged (playerIndex, gameTime)); } if(settings.moveTimingEnabled()) { listeners.forEach(listener -> listener.moveTimeChanged (playerIndex, moveTime)); } startTime = System.currentTimeMillis(); } }; timer.scheduleAtFixedRate(timeUpdateSender, 0, 100); }
public static void main(String []s) { final Dialog fd = new Dialog(new Frame(), true); Timer t = new Timer(); t.schedule(new TimerTask() { public void run() { System.out.println("RUNNING TASK"); fd.setVisible(false); fd.dispose(); System.out.println("FINISHING TASK"); } }, 3000L); fd.setVisible(true); t.cancel(); Util.waitForIdle(null); AbstractTest.pass(); }
public static Thread runQuery(final String query, final Consumer<Boolean> success, final Consumer<BackendException> failure, final long timeout) { final Consumer<Engine> engineConsumer = engine -> { if(timeout >= 0) { new Timer().schedule(new TimerTask() { @Override public void run() { synchronized (engineLock) { if(engine == null) return; engine.cancel(); } } }, timeout); } }; return runQuery(query, success, failure, engineConsumer); }
public void startMp4(File f) { mVideoFragment = VideoFragment.newInstance(f.getPath(), true); transaction.add(R.id.init_frame, mVideoFragment, "initVideo").commit(); exitTimer = new Timer(); exitTimer.schedule(new TimerTask() { @Override public void run() { videoTime--; InitStartActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if (exitInit != null) { exitInit.setText(mWeApplication.getResources().getString(R.string.exit_init) + videoTime); if (videoTime <= 0) { HomeActivity.show(InitStartActivity.this); InitStartActivity.this.finish(); } } } }); } }, 0, 1 * 1000); }
private void fadeOut() { cancelFadeTasks(); if (musicPlayer != null && volume > 0.1f) { fadeOutTask = new TimerTask() { @Override public void run() { if (musicPlayer != null) { volume -= 0.1f; if (volume < 0.1f) { cancel(); } try { musicPlayer.setVolume(volume, volume); } catch (IllegalStateException e) { e.printStackTrace(); } } } }; timer.schedule(fadeOutTask, 0, 100); } }
private void fadeIn() { cancelFadeTasks(); if (musicPlayer != null && volume < 0.9f) { fadeInTask = new TimerTask() { @Override public void run() { if (musicPlayer != null) { volume += 0.1f; if (volume > 0.9f) { cancel(); } try { musicPlayer.setVolume(volume, volume); } catch (IllegalStateException e) { e.printStackTrace(); } } } }; timer.schedule(fadeInTask, 0, 100); } }
@Override public void onFinish() { // 如果计时器正常结束,则开始计步 time.cancel(); StepSensorBase.CURRENT_STEP += TEMP_STEP; lastStep = -1; Log.v(TAG, "计时正常结束"); timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { if (lastStep == StepSensorBase.CURRENT_STEP) { timer.cancel(); CountTimeState = 0; lastStep = -1; TEMP_STEP = 0; Log.v(TAG, "停止计步:" + StepSensorBase.CURRENT_STEP); } else { lastStep = StepSensorBase.CURRENT_STEP; } } }; timer.schedule(task, 0, 2000); CountTimeState = 2; }
public Batcher(BatchedAction<T> action, long interval, final Handler handler){ this.interval = interval; if (handler != null) this.handler = new WeakReference<Handler>(handler); timerTask = new TimerTask() { @Override public void run() { if (pulled && !toHold()) { trigger(); } } }; timer.scheduleAtFixedRate(timerTask, this.interval, this.interval); setBatchedAction(action); }
@Override protected void stopItem(PlayableItem playableItem) { // Communicating with the activity is only possible after the activity // is started // if we send an broadcast event to early the activity won't be up // because there is no known way to query the activity state // we are sending the command delayed commandExecutionTimer = new Timer(); commandExecutionTimer.schedule(new TimerTask() { @Override public void run() { Intent intent = new Intent(); intent.setAction(BackgroundMusicBroadcastReceiver.ACTION_STOP); getContext().sendBroadcast(intent); } }, 600L); }
/** * Monitor only deadlocks. */ public ThreadWarningSystem() { threadCheck.schedule(new TimerTask() { @Override public void run() { long[] ids = mbean.findMonitorDeadlockedThreads(); if (ids != null && ids.length > 0) { for (Long l : ids) { if (!deadlockedThreads.contains(l)) { deadlockedThreads.add(l); ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH); fireDeadlockDetected(ti); } } } } }, 10, DEADLOCK_CHECK_PERIOD); }
private void startTimer() { Log.d("TimerManager", "Start Timer"); if (this.secondsTimer == null) { final Handler handler = new Handler() { public void handleMessage(Message msg) { TimerTextRefreshManager.this.fireOnRefreshTime(); } }; this.secondsTimer = new Timer(); this.secondsTimer.scheduleAtFixedRate(new TimerTask() { public void run() { handler.obtainMessage().sendToTarget(); } }, new Date(), 10000); } }
public void run() { Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { gameModel.tick(); if(gameModel.gameOver()) { manager.gameOver(); } if (gameModel.passedLevel() && gameModel.hasNextLevel()) { manager.passedLevel(); //screen de next kevel } else { manager.gameWon(); } } }; timer.schedule(task, 0, 5); }
public void addButton(String text) { Button button = new Button(getContext()); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -1); button.setText(text); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (commonCallBack != null) { int index = mLinearLayout.indexOfChild(v); commonCallBack.onEvent(index); } } }); mLinearLayout.addView(button, params); mTimer.schedule(new TimerTask() { @Override public void run() { fullScroll(FOCUS_RIGHT); } }, 100L); }
public void processDialogTimeout(DialogTimeoutEvent timeoutEvent) { System.out.println("processDialogTerminated " + timeoutEvent.getDialog()); DialogTimeoutEvent dialogAckTimeoutEvent = (DialogTimeoutEvent)timeoutEvent; Dialog timeoutDialog = dialogAckTimeoutEvent.getDialog(); if(timeoutDialog == null){ TxTimeoutTest.fail( "Shootist: Exception on timeout, dialog shouldn't be null"); stateIsOk = false; return; } if(dialogAckTimeoutEvent.getReason() == Reason.AckNotReceived) { stateIsOk = true; } if(dialogAckTimeoutEvent.getReason() == Reason.EarlyStateTimeout && !sendOK) { stateIsOk = true; } TimerTask timerTask = new CheckAppData(timeoutDialog); new Timer().schedule(timerTask, 9000); }
@Override public boolean scheduleWork(String workName, AbstractTimerWork r, Date firstDate, long period) { if (checkNull(workName, r, firstDate, period)) { return false; } Timer t = new Timer(workName, r.isDaemon()); r.setTimer(t); r.setPeriod(period); TimerTask tt = createTimerTask(workName, r); try { t.scheduleAtFixedRate(tt, firstDate, period); return true; } catch (Exception e) { log.err(this, "Timer Worker[" + r.getName() + "] starts FAIL.", e); } return false; }
public static void main(String[] args) { new Timer().schedule(new TimerTask() { @Override public void run() { System.err.println("Aborting"); System.exit(0); } }, 5000); // Terminate after 5 seconds ExecutorService exec = Executors.newCachedThreadPool(); AtomicIntegerTest ait = new AtomicIntegerTest(); exec.execute(ait); while (true) { int val = ait.getValue(); if (val % 2 != 0) { System.out.println(val); System.exit(0); } } }
@Override public boolean scheduleWork(String workName, AbstractTimerWork r, long delay, long period) { if (workName == null || "".equals(workName) || r == null || period < 0) { return false; } Timer t = new Timer(workName, r.isDaemon()); r.setTimer(t); r.setPeriod(period); TimerTask tt = createTimerTask(workName, r); try { t.scheduleAtFixedRate(tt, delay, period); return true; } catch (Exception e) { log.err(this, "Timer Worker[" + r.getName() + "] starts FAIL.", e); } return false; }
private static void startThreadAudit() { /// Timer class used to periodically audit the stack class AuditTimer extends TimerTask { /// Action to be performed by this timer task public final void run() { // That's all we need to do in order to check if the internal threads of the stack are healthy String auditReport = ((SIPTransactionStack) sipStack).getThreadAuditor().auditThreads(); if (auditReport != null) { System.out.println("--> RED ALERT!!! " + auditReport); } else { System.out.println("--> Internal threads of the stack appear to be healthy..."); } // Schedule the next audit timer.schedule(new AuditTimer(), auditIntervalInMillis); } } // Kick off the audit timer timer.schedule(new AuditTimer(), auditIntervalInMillis); }
private void init() { // 初始化时分秒值, second = calendar.get(Calendar.SECOND); minute = calendar.get(Calendar.MINUTE); hour = calendar.get(Calendar.HOUR_OF_DAY); timer.schedule(new TimerTask() { @Override public void run() { if (!isPause) { postInvalidate(); refreshTime(); } } }, 0, 1000); }
private void initTimer() { mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { //Timer子线程更新UI post(new Runnable() { @Override public void run() { if (mViewPager.getRealCurrentItem() == mViewPager.getRealAdapter().getCount() - 1) { mViewPager.setCurrentItem(mViewPager.getItemFirstAppearPosition(0), false); } else { mViewPager.setCurrentItem(mViewPager.getRealCurrentItem() + 1, true); } } }); } }, 0, 3000); }
/** * 添加计时器 * * @param message * @param seconds */ private void addTimerTask(final IMMessage message, int seconds) { LogUtil.printf("添加计时器"); Timer timer = new Timer(); mTimerMap.put(message.getTimeStamp(), timer); //发送时间30s; timer.schedule(new TimerTask() { @Override public void run() { message.setStatus(Status.FAILED); getMvpView().onSendMessageResult(); IMSQLManager.updateMessageSendStatus(getMvpView().getContext(), Status.FAILED, message.getTimeStamp()); } }, seconds); }
private void startPortfolioTimer() { portfolioTimer = new Timer("portfolio", false); portfolioTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { DPortfolioProducts portfolio = degiro.getPortfolio(); boolean newActiveProducts = mergeProducts(portfolio.getActive()); boolean newInactiveProducts = mergeProducts(portfolio.getInactive()); inactiveComponents.remove(PORTFOLIO); if (portfolio.getActive().size() + portfolio.getInactive().size() == 0) { inactiveComponents.remove(DESCRIPTION); inactiveComponents.remove(PRICES); } DLog.ENGINE.info("Portfolio refresh completed: " + portfolio.getActive().size() + " active, " + portfolio.getInactive().size() + " inactive."); if (newActiveProducts || newInactiveProducts) { fetchDescriptions(); } } catch (Exception e) { DLog.ENGINE.error("Exception while refreshing portfolio", e); } } }, config.getPortfolioRefreshInterval() * 1000, config.getPortfolioRefreshInterval() * 1000); }
public static void init() { cancelAll(); //changeDateTimer.cancel(); Vector events = (Vector)EventsManager.getActiveEvents(); _timers = new Vector(); /*DEBUG*/System.out.println("----------"); for (int i = 0; i < events.size(); i++) { Event ev = (Event)events.get(i); Date evTime = ev.getTime(); /*DEBUG*/System.out.println((Calendar.getInstance()).getTime()); // if (evTime.after(new Date())) { if (evTime.after((Calendar.getInstance()).getTime())) { EventTimer t = new EventTimer(ev); t.schedule(new NotifyTask(t), ev.getTime()); _timers.add(t); /*DEBUG*/System.out.println(ev.getTimeString()); } } /*DEBUG*/System.out.println("----------"); Date midnight = getMidnight(); changeDateTimer.schedule(new TimerTask() { public void run() { init(); this.cancel(); } }, midnight); notifyChanged(); }
private void startCacheCheck(long checkInterval) { mCacheCheckTimer.schedule(new TimerTask() { @Override public void run() { checkCache(); } }, 0, checkInterval); }
public IPCExecutionListener(ClientProcess client) { this.client = client; //start a timer to periodically send our live output to our server liveOutputTimer = new Timer(); liveOutputTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { sendLiveOutput(); } }, 500, 500); }
public ElasticsearchDAO(ESClient esClient, String indexName, String typeName) { this.esClient = esClient; this.indexName = indexName; this.typeName = typeName; initClient(esClient); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { while(queue.size() > 0) index(queue.remove()); } }, 3000, 1000); }
public LoadTimer() { new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { LoadTimer.this.sendLoad(); } }, 30 * 1000, 30 * 1000); }
@Test public void scheduleTaskTest() throws InterruptedException { Timer timer = mock(Timer.class); consumerManager.setTimer(timer); TimerTask timerTask = mock(TimerTask.class); consumerManager.scheduleTask(timerTask, Duration.ZERO); verify(timer).schedule(timerTask, 0); }
public void startHost() { Task<Void> task = new Task() { @Override protected Void call() throws Exception { host.start(); return null; } @Override protected void succeeded() { new Timer().schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> { TesterHost thost = (TesterHost) host; thost.execute(); try { Parent root = FXMLLoader.load(getClass().getResource("/ussd/fxml/USSD-GUI.fxml")); Stage st = UssdClient.st; st.setScene(new Scene(root)); st.centerOnScreen(); } catch (IOException ex) { Logger.getLogger(Impl.class.getName()).log(Level.SEVERE, null, ex); } }); } }, 10000); } }; new Thread(task).start(); }
public void timecount() { timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { if (stopTimer) { timer.cancel(); } else { delegate.getActivity().runOnUiThread(new Runnable() { @Override public void run() { secondcount--; delegate.getSmsView().setClickable(false); delegate.getSmsView().setText("已发送(" + secondcount + "S)"); if (secondcount == 0) { secondcount = 60; delegate.getSmsView().setClickable(true); delegate.getSmsView().setText("获取验证码"); delegate.getSmsView().setClickable(true); timer.cancel(); } } }); } } }; timer.schedule(timerTask, 1000, 1000); }