/** * 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! }
private void updateTime() { Timer commandExecutionTimer = new Timer(); commandExecutionTimer.schedule(new TimerTask() { @Override public void run() { doSetTrackInfo(); if (updateTime) { updateTime(); } } }, 1000L); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Timer timer = new Timer(); TimerTask updateTask = new TimerTask() { @Override public void run() { executeUpdate(); } }; TimerTask scrollTask = new TimerTask() { @Override public void run() { scrollTab(); } }; timer.schedule(updateTask, 1, 240000); // timer.schedule(scrollTask, 10000, 10000); }
private void startSubmitting() { // We use a timer cause want to be independent from the server tps final Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?) if (!Sponge.getPluginManager().isLoaded(plugin.getId())) { timer.cancel(); return; } // The data collection (e.g. for custom graphs) is done sync // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) Scheduler scheduler = Sponge.getScheduler(); Task.Builder taskBuilder = scheduler.createTaskBuilder(); taskBuilder.execute(() -> submitData()).submit(plugin); } }, 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! }
@Override public void stop() { // 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 // in order 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(ImageViewerBroadcastReceiver.ACTION_STOP); context.sendBroadcast(intent); } }, getExecutionTime()); }
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 void run() { //键盘监听 keyListener(); //生成下一个落下的方格 createAction(); //方格进入游戏区 enterAction(); Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { //方格下落及合并 addAction(); } }, 100, 20); }
/** * 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() { // 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 ;) FMLCommonHandler.instance().getMinecraftServerInstance().processQueue.add(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! }
ConnectionManager() { this.idleScanTimer = new Timer( "IPC Server idle connection scanner for port " + getPort(), true); this.idleScanThreshold = conf.getInt( CommonConfigurationKeysPublic.IPC_CLIENT_IDLETHRESHOLD_KEY, CommonConfigurationKeysPublic.IPC_CLIENT_IDLETHRESHOLD_DEFAULT); this.idleScanInterval = conf.getInt( CommonConfigurationKeys.IPC_CLIENT_CONNECTION_IDLESCANINTERVAL_KEY, CommonConfigurationKeys.IPC_CLIENT_CONNECTION_IDLESCANINTERVAL_DEFAULT); this.maxIdleTime = 2 * conf.getInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_KEY, CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_DEFAULT); this.maxIdleToClose = conf.getInt( CommonConfigurationKeysPublic.IPC_CLIENT_KILL_MAX_KEY, CommonConfigurationKeysPublic.IPC_CLIENT_KILL_MAX_DEFAULT); this.maxConnections = conf.getInt( CommonConfigurationKeysPublic.IPC_SERVER_MAX_CONNECTIONS_KEY, CommonConfigurationKeysPublic.IPC_SERVER_MAX_CONNECTIONS_DEFAULT); // create a set with concurrency -and- a thread-safe iterator, add 2 // for listener and idle closer threads this.connections = Collections.newSetFromMap( new ConcurrentHashMap<Connection,Boolean>( maxQueueSize, 0.75f, readThreads+2)); }
public void isStartTimer() { secondleft = 60; timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { secondleft--; int progress = (int) ((60 - secondleft) * (100 / 60.0)); if(progress<=100){ timerText = getResources().getString(R.string.finding_smart_tv,progress)+ "%)"; mHandler.sendEmptyMessage(HandlerKey.TIMER_TEXT.ordinal()); } } }, 1000, 1000); }
public void await() { if(0 == delay) { log.info("No pause between retry"); return; } final Timer wakeup = new Timer(); final CyclicBarrier wait = new CyclicBarrier(2); // Schedule for immediate execution with an interval of 1s wakeup.scheduleAtFixedRate(new PauserTimerTask(wait), 0, 1000); try { // Wait for notify from wakeup timer wait.await(); } catch(InterruptedException | BrokenBarrierException e) { log.error(e.getMessage(), e); } }
@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; }
private BroadcastReceiver defineBroadcastReceiverFor(final FlowableEmitter<SensorRecord> subscriber){ return new BroadcastReceiver() { Timer timer = new Timer(); long prevCallTime = new Date().getTime(); @Override public void onReceive(Context context, Intent intent) { long actualTime = new Date().getTime(); long delay = calculateDiffDelay(prevCallTime, actualTime); prevCallTime = actualTime; subscriber.onNext(new WifiMeasurementsRecord(wifiManager.getScanResults())); if (delay > 0) timer.schedule(createScanTask(), delay); else createScanTask().run(); } }; }
/** * 倒计时 */ private void countTime() { mTimer = new Timer(); mTask = new TimerTask() { @Override public void run() { mSeconds = mSeconds - 1; Message msg = Message.obtain(); msg.what = 1; msg.obj = mSeconds; mTimeHandler.sendMessage(msg); } }; mTimer.schedule(mTask, 0, 1000); }
private void updateSeekBar() { mTimer = new Timer(); TextView currentPosition = (TextView) findViewById(R.id.current_position); final TextView duration = (TextView) findViewById(R.id.duration); if (playService != null) { duration.setText(toTime(playService.getDuration())); } TimerTask task = new TimerTask() { @Override public void run() { if (playService != null) { if (Data.getDuration(Data.getPosition()) == 0){ seekBar.setMax(Data.getMediaDuration()); } if (Data.getState() == playing) { seekBar.setProgress(playService.getCurrentPosition()); } } } }; mTimer.schedule(task, 0, 1000); }
private void scheduleHalt() { try { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { Runtime.getRuntime().halt(1); } }, 10000L); System.exit(1); } catch (Throwable var2) { Runtime.getRuntime().halt(1); } }
public void startInterval() { new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { playSeekerReleaseCountdownSoundIfTime(game.clocks[game.activeTime].getElapsedTime()); runOnUiThread(new Runnable() { @Override public void run() { //long startTime = System.nanoTime(); penaltyDataSetHasChanged(); //long midTime = System.nanoTime(); //sysout(midTime-startTime); if(game.activeTime == 1) if(game.clocks[game.activeTime].getTimeRemaining() == 0) pauseWatches(); updateClockUI(); updateChangePenaltyCountdown(); // updates alle watches in change penalty views (where you can change a penalty) showSnitchesIfTimeReady(); showGetSnitchReadyAlert(); showFirstOvertimeShoutAlerts(); //long endTime = System.nanoTime(); //sysout(endTime-startTime); //sysout("OVER"); } }); } },0,100); }
public LogReader() { changeSupport = new PropertyChangeSupport(this); listeners = new HashSet<>(); adb = AndroidSdkProvider.getAdb(); checkReadingStatusTimer = new Timer(); checkReadingStatusTimer.schedule(new TimerTask() { @Override public void run() { try { if (!shouldBeReading) { return; } if (!deviceReallyConnected()) { infoMessage("Trying to reconnect to the device in " + checkingPeriod / 1000 + " seconds."); startReading(); } } catch (Exception e) { LOG.log(Level.SEVERE, "Unexpected exception on reconnecting the device.", e); } } }, checkingPeriod, checkingPeriod); }
@OnClick(R.id.btn_progress_dialog_simple) public void onBtnProgressDialogSimpleClicked() { final int[] progress = {0}; final ProgressDialog dialog = new ProgressDialog(this); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.show(); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { progress[0] += 10; dialog.setProgress(progress[0]); if (progress[0] >= 100) { ToastUtils.showShortToast("加载完成"); timer.cancel(); dialog.dismiss(); } } }, 0, 500); }
private void animateProgress(final HomeItem item, final Timer timer, RootInfo root){ try { final double percent = (((root.totalBytes - root.availableBytes) / (double) root.totalBytes) * 100); item.setProgress(0); timer.schedule(new TimerTask() { @Override public void run() { if(Utils.isActivityAlive(getActivity())){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (item.getProgress() >= (int) percent) { timer.cancel(); } else { item.setProgress(item.getProgress() + 1); } } }); } } }, 50, 20); } catch (Exception e){ item.setVisibility(View.GONE); CrashReportingManager.logException(e); } }
public static void selfDestruct(Message message, long delay) { if (message == null) return; new Timer().schedule(new TimerTask() { @Override public void run() { message.delete().complete(); } }, delay); }
@Override public void startCountDown() { countDownTimer = new Timer(); countDownTimer.schedule(new TimerTask() { private int i = 0; @Override public void run() { if (++i > 10) { stopCountDown(); mHandler.sendEmptyMessage(NaviSetLineActivity.MSG_START_NAV); } else { Message msg = new Message(); msg.what = NaviSetLineActivity.MSG_UPDATE_COUNTDOWN; msg.arg1 = 10 - i; mHandler.sendMessage(msg); } } }, 1000, 1000); }
public void onGuildJoin(GuildJoinEvent event) { Guild g = event.getGuild(); SQL.createServer(g); System.out.println("[Amme]System started on: " + g.getName()); Guild guild = event.getGuild(); GuildController controller = guild.getController(); new Timer().schedule(new TimerTask() { @Override public void run() { controller.createCategory("Amme").queue(cat -> { controller.modifyCategoryPositions() .selectPosition(cat.getPosition()) .moveTo(0).queue(); String[] list = {"music", "commands", "log", "randomstuff"}; Arrays.stream(list).forEach(s -> controller.createTextChannel(s).queue(chan -> chan.getManager().setParent((Category) cat).queue()) ); }); SQL.updateValue(guild, "music", event.getGuild().getTextChannelsByName("music", true).get(0).getName()); SQL.updateValue(guild, "logchannel", event.getGuild().getTextChannelsByName("log", true).get(0).getId()); SQL.updateValue(guild, "joinchannel", event.getGuild().getTextChannelsByName("randomstuff", true).get(0).getId()); } }, 5000); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setFullscreen(); setContentView(R.layout.activity_background); final Intent intent = new Intent("com.pyy.signin.activity_main"); Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { startActivity(intent); //执行 WelcomePage.this.finish(); } }; timer.schedule(task, 1000 * 2); //2秒后 }
public TaskScheduler(long delay, OnTaskStateListener listener) { mListener = listener; mStartTime = System.currentTimeMillis(); mDelay = delay; Task task = new Task(mListener); mTaskExecutor = new Timer(); mTaskExecutor.schedule(task, mDelay); }
/** * Find a timer for the given server. * * @param si The new {@code ServerInfo} to look for. * @return The {@code Timer} found if any. */ private static Timer findTimer(final ServerInfo si) { Entry<Timer, ServerInfo> entry = find(updaters.entrySet(), matchKeyEquals(si.getName(), (Entry<Timer,ServerInfo> e) -> e.getValue().getName())); return (entry == null) ? null : entry.getKey(); }
public void start() { new Timer("Netty-Pinger").scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (channel.isOpen()) channel.writeAndFlush(new PacketPing(System.currentTimeMillis())); } }, 1000L, this.interval * 1000L); }
@Override protected void copyData(InputStream inputStream, OutputStream outputStream) throws IOException { final CountingOutputStream countingOutputStream = new CountingOutputStream(outputStream); Timer timer = new Timer(); try { timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { progressListener.updateProgress(countingOutputStream.getCount()); } }, 0, 50); super.copyData(inputStream, countingOutputStream); } finally { timer.cancel(); } }
private void setUpdateTimer(final ArrayList<Marker> otherUserMarkers, final ArrayList<User> initializedUsers) { // Fetch user locations with a fixed interval, to prevent starting too many threads. timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { FirebaseHelper.groupDelegate = MapFragment.this; FirebaseHelper.photoDelegate = MapFragment.this; // Check if enough users are loaded, only then the locations of these users can // be updated. if (otherUserMarkers.size() == initializedUsers.size()) { FirebaseHelper.updateLocations(userIDs, otherUserMarkers, currentMarker); } } }, 0, INTERVAL); }
@Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (!RubiconBot.getMySQL().verificationEnabled(event.getGuild())) return; TextChannel channel = event.getGuild().getTextChannelById(RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "channelid")); Message message = channel.sendMessage(new EmbedBuilder().setDescription(RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "text").replace("%user%", event.getUser().getAsMention())).build()).complete(); CommandVerification.users.put(message, event.getUser()); String emoteRaw = RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "emote"); if (!isNumeric(emoteRaw)) message.addReaction(emoteRaw).queue(); else message.addReaction(event.getJDA().getEmoteById(emoteRaw)).queue(); Role verified = event.getGuild().getRoleById(RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "roleid")); int delay = Integer.parseInt(RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "kicktime")); if (delay == 0) return; new Timer().schedule(new TimerTask() { @Override public void run() { if (!event.getMember().getRoles().contains(verified)) { event.getUser().openPrivateChannel().complete().sendMessage(RubiconBot.getMySQL().getVerificationValue(event.getGuild(), "kicktext").replace("%user%", event.getUser().getAsMention())).queue(); event.getGuild().getController().kick(event.getMember()).queue(); } } }, delay * 1000 * 60); }
private static void ifTravisCi(String[] args) { if (args.length > 1 && "-exitOnSec".equals(args[0])) { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { System.exit(0); } }; timer.schedule(timerTask, Integer.parseInt(args[1]) * 1000); } }
public void start() { Platform.runLater(() -> { try { getMediaView().setMediaPlayer(getMediaPlayer(getNextVideoFile())); } catch (FileNotFoundException ex) { QLog.l().logger().error("No content.", ex); return; } getMediaView().getMediaPlayer().setCycleCount(videoFiles.size() > 0 ? 1 : 9000000); if (videoFiles.size() > 0) { getMediaView().getMediaPlayer().setOnEndOfMedia(changer); } //getMediaView().getMediaPlayer().setMute(true); final Timer t = new Timer(true); t.schedule(new TimerTask() { @Override public void run() { try { getMediaView().getMediaPlayer().play(); javafxPanel.getComponentListeners()[0].componentResized(null); } catch (Exception npe) { QLog.l().logger().error( "Кодак не поддерживается. Codak not supported. Видео должно быть в формате H.264.", npe); } } }, 1500); }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bnp = (NumberProgressBar)findViewById(R.id.numberbar1); bnp.setOnProgressBarListener(this); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { bnp.incrementProgressBy(1); } }); } }, 1000, 100); }
/** * 执行播放任务 **/ private void startPlayTask(final PlayTrackTask trackTask) { cancelPlayTimer(); msgBuilder.setText(""); mPlayTimer = new Timer(); if (isDelay) { Single.just(0) .delay(100, TimeUnit.MILLISECONDS) .doOnSuccess(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { EventBus.getDefault().post(new UpdateWaittingSeekBarEvent(false)); mPlayTimer.schedule(trackTask, 5000); } }) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .subscribe(); } else { mPlayTimer.schedule(trackTask, 0); } }
public void shareMySheet(boolean status) { if (status) { this.timer = new Timer(); this.alarmClock = new AlarmClock(this); this.timer.scheduleAtFixedRate(this.alarmClock, 0, MainWindow.TIME); } else { this.timer.cancel(); } }
public void run(SortedListModel<MMUserStatus> listModel, String username, String password, String url) throws IOException, URISyntaxException, CertificateException, InterruptedException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { MM_URL = url; login(username, password); users(); teams(); userStatus(); ws = websocket(listModel); java.util.Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { if (ws == null || ws.isClosed()) { Notifications.Bus.notify(new Notification("team", "mattermost websocket", "websocket reconnecting...", NotificationType.INFORMATION)); ws = websocket(listModel); } ws.send("{\"action\":\"get_statuses\",\"seq\":" + (++seq) + "}"); statusSeq = seq; } catch (Throwable t) { t.printStackTrace(); Notifications.Bus.notify(new Notification("team", "mattermost Error", t.getMessage(), NotificationType.ERROR)); } } }, 5000, 60000); this.listModel = listModel; fillListModel(); }