Java Code Examples for java.util.Timer#scheduleAtFixedRate()

The following examples show how to use java.util.Timer#scheduleAtFixedRate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LibraryActivity.java    From PowerFileExplorer with GNU General Public License v3.0 7 votes vote down vote up
public void onResume() {
	super.onResume();
	TimerTask updateTask = new TimerTask() {
		public void run() {
			runOnUiThread(new Runnable() {
					public void run() {
						updateFileList();
					}
				});
		}
	};
	updateTimer = new Timer();
	updateTimer.scheduleAtFixedRate(updateTask, 0, UPDATE_DELAY);
}
 
Example 2
Source File: MainActivity.java    From circle-progress-ad-android with GNU General Public License v3.0 7 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adCircleProgress = findViewById(R.id.pgb_progress);
    adCircleProgress2 = findViewById(R.id.pgb_progress2);
    adCircleProgress3 = findViewById(R.id.pgb_progress3);
    adCircleProgress4 = findViewById(R.id.pgb_progress4);
    adCircleProgress5 = findViewById(R.id.pgb_progress5);


    final Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {


                    adCircleProgress.setAdProgress(i);
                    adCircleProgress2.setAdProgress(i);
                    adCircleProgress3.setAdProgress(i);
                    adCircleProgress4.setAdProgress(i);
                    adCircleProgress5.setAdProgress(i);
                    i++;
                }
            });
        }
    }, 0, 50);

    adCircleProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
        }
    });


}
 
Example 3
Source File: Metrics.java    From NametagEdit with GNU General Public License v3.0 7 votes vote down vote up
/**
 * 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!
}
 
Example 4
Source File: MainActivity.java    From PlayWidget with MIT License 7 votes vote down vote up
private void startTrackingPosition() {
    timer = new Timer("MainActivity Timer");
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            MediaPlayer tempMediaPlayer = mediaPlayer;
            if (tempMediaPlayer != null && tempMediaPlayer != null && tempMediaPlayer.isPlaying()) {

                mPlayLayout.setPostProgress((float) tempMediaPlayer.getCurrentPosition() / tempMediaPlayer.getDuration());
            }

        }
    }, UPDATE_INTERVAL, UPDATE_INTERVAL);
}
 
Example 5
Source File: Metrics.java    From NeuralNetworkAPI with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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!
}
 
Example 6
Source File: DelayOverflow.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
Example 7
Source File: CompassActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_compass);
  mCompassView = findViewById(R.id.compassView);

  mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

  Display display = wm.getDefaultDisplay();
  mScreenRotation = display.getRotation();

  mNewestValues = new float[] {0, 0, 0};

  Timer updateTimer = new Timer("compassUpdate");
  updateTimer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
      updateGUI();
    }
  }, 0, 1000/60);
}
 
Example 8
Source File: Tracking.java    From Finder with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    tracking_running = true;
    phone = intent.getStringExtra("phone");
    sms_number = Integer.parseInt(intent.getStringExtra("tracking_sms_max_number"));
    delay = Integer.parseInt(intent.getStringExtra("tracking_delay"));
    sms_buffer_max = Integer.parseInt(intent.getStringExtra("tracking_coord_number"));
    accuracy = Integer.parseInt(intent.getStringExtra("tracking_accuracy"));
    String name = intent.getStringExtra("name");

    timer = new Timer();
    TrackingTask trackTask = new TrackingTask();  //timer for regular getting coords
    timer.scheduleAtFixedRate(trackTask, 0L, 1000L*delay);  //5 minutes default
    stop.postDelayed(full_stopper, sms_number * sms_buffer_max * delay * 1500L);  //stop this service when work time more than 1.5 times then calculated (to save battery) (1500L = 1000ms * 1.5)

    //only one tracking can work, so this code will be called only once
    Intent notifIntent = new Intent(this, TrackStatus.class);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notifIntent, 0);
    builder = new NotificationCompat.Builder(this, MainActivity.TRACKING_NOTIF_CHANNEL);
    builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.tracking_on_notify, name))  //"name" gets from intent - this is reason using onStartCommand instead onCreate
            .setContentText(getString(R.string.sms_sent, 0))
            .setContentIntent(pendIntent);
    startForeground(1, builder.build());  //id 1 for tracking, 2,3,4.. for others

    return START_REDELIVER_INTENT;
}
 
Example 9
Source File: ExecuteGradleCommandClientProtocol.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example 10
Source File: AsyncRequestPersistence.java    From JavaConcurrencyPattern with MIT License 5 votes vote down vote up
private AsyncRequestPersistence() {
	logger = Logger.getLogger(AsyncRequestPersistence.class);
	scheduler = new ThreadPoolExecutor(1, 3, 60 * ONE_MINUTE_IN_SECONDS,
	    TimeUnit.SECONDS,
	    // ActiveObjectPattern.ActivationQueue
	    new LinkedBlockingQueue<Runnable>(200), new ThreadFactory() {
		    @Override
		    public Thread newThread(Runnable r) {
			    Thread t;
			    t = new Thread(r, "AsyncRequestPersistence");
			    return t;
		    }

	    });

	scheduler
	    .setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());

	// 启动队列监控定时任务
	Timer monitorTimer = new Timer(true);
	monitorTimer.scheduleAtFixedRate(new TimerTask() {

		@Override
		public void run() {
			if (logger.isInfoEnabled()) {

				logger.info("task count:" + requestSubmittedPerIterval
				    + ",Queue size:" + scheduler.getQueue().size()
				    + ",taskTimeConsumedPerInterval:"
				    + taskTimeConsumedPerInterval.get() + " ms");
			}

			taskTimeConsumedPerInterval.set(0);
			requestSubmittedPerIterval.set(0);

		}
	}, 0, ONE_MINUTE_IN_SECONDS * 1000);

}
 
Example 11
Source File: SimplePerformanceMeter.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
public void registerListener() {
    animationTimer.start();
    timer = new Timer("SimplePerformanceMeter-timer", true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            final long timerIterationThis = System.currentTimeMillis();
            final int pulseCount = pulseCounter.getAndSet(0);
            final int frameCount = frameCounter.getAndSet(0);
            final double diff = (timerIterationThis - timerIterationLast) * 1e-3;
            timerIterationLast = timerIterationThis;
            pulseRateInternal = diff > 0 ? pulseCount / diff : -1;
            frameRateInternal = diff > 0 ? frameCount / diff : -1;
            // alt via fxPerformanceTracker - keep for the future in case this becomes public
            pulseRateInternal = fxPerformanceTracker.getInstantPulses();
            frameRateInternal = fxPerformanceTracker.getInstantFPS();

            cpuLoadProcessInternal = OS_BEAN.getProcessCpuLoad() * 100 * N_CORES;
            cpuLoadSystemInternal = OS_BEAN.getSystemCpuLoad() * 100 * N_CORES;
            // alt via non sun classes - keep for the future in case this becomes public
            // cpuLoadProcessInternal = getProcessCpuLoadInternal() * N_CORES;
            // cpuLoadSystemInternal = OS_BEAN.getSystemLoadAverage() * N_CORES;

            final double alpha = averageFactor.get();
            pulseRateAvgInternal = computeAverage(pulseRateInternal, pulseRateAvgInternal, alpha);
            frameRateAvgInternal = computeAverage(frameRateInternal, frameRateAvgInternal, alpha);
            cpuLoadProcessAvgInternal = computeAverage(cpuLoadProcessInternal, cpuLoadProcessAvgInternal, alpha);
            cpuLoadSystemAvgInternal = computeAverage(cpuLoadSystemInternal, cpuLoadSystemAvgInternal, alpha);

            FXUtils.runFX(SimplePerformanceMeter.this::updateProperties);
        }
    }, 0, updateDuration);
    scene.addPostLayoutPulseListener(pulseListener);
}
 
Example 12
Source File: DeviceSensor.java    From iot-starter-for-android with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Register the listeners for the sensors the application is interested in.
 */
public void enableSensor() {
    Log.i(TAG, ".enableSensor() entered");
    if (!isEnabled) {
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
        tripId = System.currentTimeMillis()/1000;
        timer = new Timer();
        timer.scheduleAtFixedRate(new SendTimerTask(), 1000, 1000);
        isEnabled = true;
    }
}
 
Example 13
Source File: SnakeTimer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public static void startTimer() {
    gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer");
    gameTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                tick();
            } catch (RuntimeException e) {
                log.error("Caught to prevent timer from shutting down", e);
            }
        }
    }, TICK_DELAY, TICK_DELAY);
}
 
Example 14
Source File: PlainTerracottaJobStore.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void scheduleUpdateCheck() {
  if (!Boolean.getBoolean("org.terracotta.quartz.skipUpdateCheck")) {
    updateCheckTimer = new Timer("Update Checker", true);
    updateCheckTimer.scheduleAtFixedRate(new UpdateChecker(), 100, WEEKLY);
  }
}
 
Example 15
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update checker scheduler - fires every week
 */
private Timer scheduleUpdateCheck() {
    Timer rval = new Timer(true);
    rval.scheduleAtFixedRate(new UpdateChecker(), 1000, 7 * 24 * 60 * 60 * 1000L);
    return rval;
}
 
Example 16
Source File: Consumer.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MQClientException {
    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps =
                        (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = ((end[2] - begin[2]) / (double) (end[1] - begin[1]));
                final double averageS2CRT = ((end[3] - begin[3]) / (double) (end[1] - begin[1]));

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n"//
                        , consumeTps//
                        , averageB2CRT//
                        , averageS2CRT//
                        , end[4]//
                        , end[5]//
                );
            }
        }


        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer =
            new DefaultMQPushConsumer("benchmark_consumer_"
                    + Long.toString(System.currentTimeMillis() % 100));
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe("BenchmarkTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                        ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            // 1
            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            // 2
            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            // 3
            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            // 4
            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            // 5
            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}
 
Example 17
Source File: MindViewer.java    From cst with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void StartTimer() {
    Timer t = new Timer();
    WOVTimerTask tt = new WOVTimerTask(this);
    t.scheduleAtFixedRate(tt, 0, 3000);
}
 
Example 18
Source File: LocalPlayerActivity.java    From android with Apache License 2.0 4 votes vote down vote up
private void restartTrickplayTimer() {
    stopTrickplayTimer();
    mSeekbarTimer = new Timer();
    mSeekbarTimer.scheduleAtFixedRate(new UpdateSeekbarTask(), 100, 1000);
    Log.d(TAG, "Restarted TrickPlay Timer");
}
 
Example 19
Source File: PollingModule.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void doStart() throws OpenAS2Exception {
    timer = new Timer(getName(), false);
    timer.scheduleAtFixedRate(new PollTask(), 0, getInterval() * 1000);
}
 
Example 20
Source File: FpsCounter.java    From J2ME-Loader with Apache License 2.0 4 votes vote down vote up
public FpsCounter(View view) {
	this.view = view;
	mTimer = new Timer("FpsCounter", true);
	mTimer.scheduleAtFixedRate(this, 0, 1000);
}