Java Code Examples for java.util.TimerTask

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project facebook-android-sdk, under directory /examples/Hackbook/src/com/facebook/android/.

Source file: SplashActivity.java

  34 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.splash);
  TimerTask task=new TimerTask(){
    @Override public void run(){
      finish();
      Intent hackbookIntent=new Intent().setClass(SplashActivity.this,Hackbook.class);
      startActivity(hackbookIntent);
    }
  }
;
  Timer timer=new Timer();
  timer.schedule(task,splashDelay);
}
 

Example 2

From project java-cas-client, under directory /cas-client-core/src/test/java/org/jasig/cas/client/proxy/.

Source file: CleanUpTimerTaskTest.java

  33 
vote

public void testRun() throws Exception {
  final ProxyGrantingTicketStorageTestImpl storage=new ProxyGrantingTicketStorageTestImpl();
  new Cas20ProxyReceivingTicketValidationFilter().setProxyGrantingTicketStorage(storage);
  final TimerTask timerTask=new CleanUpTimerTask(storage);
  timerTask.run();
  assertTrue(storage.cleanUpWasCalled());
}
 

Example 3

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: Scheduler.java

  32 
vote

public static synchronized void cancel(Runnable task){
  TimerTask ticket=TIMER_TASKS.remove(task);
  if (ticket != null) {
    ticket.cancel();
    CLOCK_DAEMON.purge();
  }
}
 

Example 4

From project commons-pool, under directory /src/java/org/apache/commons/pool/.

Source file: PoolUtils.java

  32 
vote

/** 
 * Periodically check the idle object count for the pool. At most one idle object will be added per period. If there is an exception when calling  {@link ObjectPool#addObject()} then no more checks will be performed.
 * @param pool the pool to check periodically.
 * @param minIdle if the {@link ObjectPool#getNumIdle()} is less than this then add an idle object.
 * @param period the frequency to check the number of idle objects in a pool, see{@link Timer#schedule(TimerTask,long,long)}.
 * @return the {@link TimerTask} that will periodically check the pools idle object count.
 * @throws IllegalArgumentException when <code>pool</code> is <code>null</code> orwhen <code>minIdle</code> is negative or when <code>period</code> isn't valid for  {@link Timer#schedule(TimerTask,long,long)}.
 * @since Pool 1.3
 */
public static TimerTask checkMinIdle(final ObjectPool pool,final int minIdle,final long period) throws IllegalArgumentException {
  if (pool == null) {
    throw new IllegalArgumentException("keyedPool must not be null.");
  }
  if (minIdle < 0) {
    throw new IllegalArgumentException("minIdle must be non-negative.");
  }
  final TimerTask task=new ObjectPoolMinIdleTimerTask(pool,minIdle);
  getMinIdleTimer().schedule(task,0L,period);
  return task;
}
 

Example 5

From project harmony, under directory /harmony.adapter.uclp/src/main/java/org/opennaas/extensions/idb/da/argia/webservice/.

Source file: StartupServlet.java

  32 
vote

/** 
 * This function programs the polling of the Endpoints to the NRPS server. It starts NOW and gets the polling interval from the "uclp.properties" configuration file
 */
private void schedulePolling(){
  StartupServlet.logger.info("Starting polling scheduler...");
  final TimerTask timerTask=new TimerTask(){
    @Override public void run(){
      StartupServlet.this.pullEndpoints();
    }
  }
;
  final Timer timer=new Timer();
  final long interval=Long.parseLong(Config.getString("uclp","nrps.pollingInterval"));
  final long delay=Long.parseLong(Config.getString("uclp","nrps.pollingDelayBeforeExecution"));
  timer.scheduleAtFixedRate(timerTask,delay,interval);
  StartupServlet.logger.info("Polling scheduler started successfully! (each " + interval / 1000 + " seconds with an initial delay of " + delay / 1000);
}
 

Example 6

From project jPOS, under directory /jpos/src/test/java/org/jpos/transaction/.

Source file: PausedTransactionTest.java

  32 
vote

@Test public void testCancelExpirationMonitor1() throws Throwable {
  TimerTask expirationMonitor=new TransactionManager.PausedMonitor(new Context());
  PausedTransaction pausedTransaction=new PausedTransaction(new TransactionManager(),100L,new ArrayList(),(new ArrayList()).iterator(),true,expirationMonitor);
  pausedTransaction.cancelExpirationMonitor();
  assertSame("pausedTransaction.expirationMonitor",expirationMonitor,junitx.util.PrivateAccessor.getField(pausedTransaction,"expirationMonitor"));
}
 

Example 7

From project MIT-Mobile-for-Android, under directory /src/edu/mit/mitmobile2/.

Source file: MITNewsWidgetActivity.java

  32 
vote

private TimerTask slideShowTimerTask(){
  final Handler myHandler=new Handler();
  TimerTask timerTask=new TimerTask(){
    @Override public void run(){
      if (news == null)       return;
      myHandler.post(mUpdateSlideShow);
    }
  }
;
  return timerTask;
}
 

Example 8

From project mobilis, under directory /DemoServices/TreasureHunt/src/de/treasurehunt/.

Source file: TreasureHunt.java

  32 
vote

private void startTreasureCollectedTimer(){
  TimerTask task=new TimerTask(){
    @Override public void run(){
      System.out.println("TreasureCollectedTimer");
      _proxy.TreasureCollected("consoleclient@xhunt/JavaClient","player1",new Location(51033880,13783272),500);
    }
  }
;
  Timer timer=new Timer();
  timer.schedule(task,10000);
}
 

Example 9

From project PocketVDC, under directory /src/sate/pocketvdc/activities/.

Source file: SplashActivity.java

  32 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_splash);
  TimerTask wait=new TimerTask(){
    @Override public void run(){
      finish();
      startActivity(new Intent(getApplicationContext(),HomeActivity.class));
    }
  }
;
  Timer timer=new Timer();
  timer.schedule(wait,3000);
}
 

Example 10

From project AlarmApp-Android, under directory /src/org/alarmapp/services/.

Source file: PositionService.java

  31 
vote

private void setupAbortTimer(){
  timer.schedule(new TimerTask(){
    @Override public void run(){
      LogEx.verbose("Abort Tracking timer has expired. Sending CancelTrackingIntent");
      PositionService.this.startService(getTrackingIntent(Actions.CANCEL_TRACKING));
    }
  }
,MAX_TRACKING_TIME);
}
 

Example 11

From project AlbiteREADER, under directory /src/org/albite/albite/.

Source file: BookCanvas.java

  31 
vote

private void startClock(){
  if (clockTimerTask == null) {
    clockTimerTask=new TimerTask(){
      public void run(){
        updateClock();
      }
    }
;
    timer.scheduleAtFixedRate(clockTimerTask,60000,60000);
  }
}
 

Example 12

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/camera/.

Source file: AutoFocusManager.java

  31 
vote

@Override public synchronized void onAutoFocus(boolean success,Camera theCamera){
  if (active && !manual) {
    outstandingTask=new TimerTask(){
      @Override public void run(){
        checkAndStart();
      }
    }
;
    timer.schedule(outstandingTask,AUTO_FOCUS_INTERVAL_MS);
  }
  manual=false;
}
 

Example 13

From project android-voip-service, under directory /src/main/java/org/linphone/.

Source file: LinphoneManager.java

  31 
vote

private synchronized void startLibLinphone(final Context context){
  try {
    copyAssetsFromPackage(context);
    mLc=LinphoneCoreFactory.instance().createLinphoneCore(this,linphoneConfigFile,linphoneInitialConfigFile,null);
    mLc.enableIpv6(mPref.getBoolean(getString(R.string.pref_ipv6_key),false));
    mLc.setZrtpSecretsCache(basePath + "/zrtp_secrets");
    mLc.setPlaybackGain(3);
    mLc.setRing(null);
    mLc.setRootCA(linphoneRootCaFile);
    try {
      initFromConf(context);
    }
 catch (    LinphoneException e) {
      Log.w("no config ready yet");
    }
    TimerTask lTask=new TimerTask(){
      @Override public void run(){
        mLc.iterate();
      }
    }
;
    mTimer.scheduleAtFixedRate(lTask,0,100);
    IntentFilter lFilter=new IntentFilter(Intent.ACTION_SCREEN_ON);
    lFilter.addAction(Intent.ACTION_SCREEN_OFF);
    context.registerReceiver(mKeepAliveReceiver,lFilter);
  }
 catch (  Exception e) {
    Log.e(e,"Cannot start linphone");
  }
}
 

Example 14

From project androidtracks, under directory /src/org/sfcta/cycletracks/.

Source file: RecordingActivity.java

  31 
vote

@Override public void onResume(){
  super.onResume();
  timer=new Timer();
  timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      mHandler.post(mUpdateTimer);
    }
  }
,0,1000);
}
 

Example 15

From project android_5, under directory /src/aarddict/android/.

Source file: DictionariesActivity.java

  31 
vote

@SuppressWarnings("unchecked") public DictListAdapter(Map<UUID,List<Volume>> volumes){
  this.volumes=new ArrayList();
  this.volumes.addAll(volumes.values());
  inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  timer.scheduleAtFixedRate(new TimerTask(){
    public void run(){
      updateView();
    }
  }
,TIME_UPDATE_PERIOD,TIME_UPDATE_PERIOD);
}
 

Example 16

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 17

From project android_packages_apps_QiblaCompass, under directory /src/com/farsitel/qiblacompass/activities/.

Source file: QiblaActivity.java

  31 
vote

private TimerTask getTimerTask(){
  TimerTask timerTask=new TimerTask(){
    @Override public void run(){
      if (angleSignaled && !ConcurrencyUtil.isAnyAnimationOnRun()) {
        Map<String,Double> newAnglesMap=qiblaManager.fetchDeltaAngles();
        Double newNorthAngle=newAnglesMap.get(QiblaCompassManager.NORTH_CHANGED_MAP_KEY);
        Double newQiblaAngle=newAnglesMap.get(QiblaCompassManager.QIBLA_CHANGED_MAP_KEY);
        Message message=mHandler.obtainMessage();
        message.what=ROTATE_IMAGES_MESSAGE;
        Bundle b=new Bundle();
        if (newNorthAngle == null) {
          b.putBoolean(IS_COMPASS_CHANGED,false);
        }
 else {
          ConcurrencyUtil.incrementAnimation();
          b.putBoolean(IS_COMPASS_CHANGED,true);
          b.putDouble(COMPASS_BUNDLE_DELTA_KEY,newNorthAngle);
        }
        if (newQiblaAngle == null) {
          b.putBoolean(IS_QIBLA_CHANGED,false);
        }
 else {
          ConcurrencyUtil.incrementAnimation();
          b.putBoolean(IS_QIBLA_CHANGED,true);
          b.putDouble(QIBLA_BUNDLE_DELTA_KEY,newQiblaAngle);
        }
        message.setData(b);
        mHandler.sendMessage(message);
      }
 else       if (ConcurrencyUtil.getNumAimationsOnRun() < 0) {
        Log.d(NAMAZ_LOG_TAG," Number of animations are negetive numOfAnimation: " + ConcurrencyUtil.getNumAimationsOnRun());
      }
    }
  }
;
  return timerTask;
}
 

Example 18

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: ErrorDisplayer.java

  31 
vote

public static void showConnectionErrorOnThread(String Message,final Context ctx,Exception e){
  Looper.prepare();
  final Looper tLoop=Looper.myLooper();
  showConnectionError(Message,ctx,e);
  final Timer t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      tLoop.quit();
      t.cancel();
    }
  }
,6000);
  Looper.loop();
}
 

Example 19

From project BetterShop_1, under directory /src/me/jascotty2/bettershop/spout/gui/.

Source file: MarketItemDetail.java

  31 
vote

private void redirtyTxtAmt(){
  if (t != null) {
    t.cancel();
    t=null;
  }
  t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      setAmt(currentAmt);
      t=null;
    }
  }
,1000);
}
 

Example 20

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/activity/social/.

Source file: ChatActivity.java

  31 
vote

public void setupTimer(){
  if (PublicUtils.isNetworkAvailable(this) && mTimerReload == null) {
    mTimerReload=new Timer();
    mTimerReload.schedule(new TimerTask(){
      @Override public void run(){
        reload();
      }
    }
,0,mSharedPreferences.getInt(Constants.SP_BL_INTERVAL_CHAT,25) * 1000);
  }
}
 

Example 21

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRestService.java

  31 
vote

/** 
 * Start rss change timer.
 */
public void startRssChangeTimer(){
  Timer timer=new Timer(true);
  timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      checkForUpdates(bioportalRssFeedClient.getBioportalRssFeed());
    }
  }
,0,ONE_MINUTE * this.cacheUpdatePeriod);
}
 

Example 22

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/fedora/.

Source file: AccessControlUtils.java

  31 
vote

public void startCacheCleanupThreadForFedoraBasedAccessControl(){
  if (cacheResetTime > 0) {
    Timer timer=new Timer();
    timer.scheduleAtFixedRate(new TimerTask(){
      @Override public void run(){
        clearAndPreloadCdrCaches(cacheDepth,cacheLimit,collectionsPid);
      }
    }
,0,cacheResetTime * 3600000);
  }
}
 

Example 23

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/writer/.

Source file: SeqFileWriter.java

  31 
vote

/** 
 * Schedules the rotate task using either a fixed time interval scheme or a relative time interval scheme as specified by the chukwaCollector.isFixedTimeRotatorScheme configuration parameter. If the value of this parameter is true then next rotation will be scheduled at a fixed offset from the current rotateInterval. This fixed offset is provided by chukwaCollector.fixedTimeIntervalOffset configuration parameter.
 */
void scheduleNextRotation(){
  long delay=rotateInterval;
  if (if_fixed_interval) {
    long currentTime=System.currentTimeMillis();
    delay=getDelayForFixedInterval(currentTime,rotateInterval,offsetInterval);
  }
  rotateTimer=new Timer();
  rotateTimer.schedule(new TimerTask(){
    public void run(){
      rotate();
    }
  }
,delay);
}
 

Example 24

From project CIShell, under directory /clients/remoting/org.cishell.reference.remoting/src/org/cishell/reference/remoting/.

Source file: CIShellClient.java

  31 
vote

public void open(String host){
  fw=new CIShellFrameworkClient();
  fw.open(host);
  sessionID=fw.createSession("localhost");
  setupEventQueue();
  RemoteDataConversionServiceClient remoteConverter=new RemoteDataConversionServiceClient();
  AttributeDefinitionRegistryClient attrReg=new AttributeDefinitionRegistryClient();
  DataModelRegistryClient dmReg=new DataModelRegistryClient(ciContext,remoteConverter);
  AlgorithmRegistryClient algReg=new AlgorithmRegistryClient(bContext,sessionID,dmReg);
  ObjectClassDefinitionRegistryClient ocdReg=new ObjectClassDefinitionRegistryClient(attrReg);
  MetaTypeProviderRegistryClient mtpReg=new MetaTypeProviderRegistryClient(ocdReg);
  AlgorithmFactoryRegistryClient algFactoryReg=new AlgorithmFactoryRegistryClient(sessionID,algReg,mtpReg,dmReg);
  remoteConverter.open(host);
  algFactoryReg.open(host);
  algReg.open(host);
  attrReg.open(host);
  dmReg.open(host);
  mtpReg.open(host);
  ocdReg.open(host);
  this.algFactoryReg=algFactoryReg;
  this.host=host;
  eventAdmin=(EventAdmin)bContext.getService(bContext.getServiceReference(EventAdmin.class.getName()));
  algToRegMap=new HashMap();
  logHandler=new LogEventHandler(bContext,sessionID);
  publishAllAlgs();
  timer=new Timer(true);
  TimerTask task=new TimerTask(){
    public void run(){
      getNewEvents();
      putEventReplies();
    }
  }
;
  timer.scheduleAtFixedRate(task,0,2000);
}
 

Example 25

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: ConnectionManager.java

  31 
vote

/** 
 * Initialise le Timer permettant de fermer une connection non utilis? au bout du closeDelay.
 */
private void initTimer(){
  timer=new Timer(true);
  timer.schedule(new TimerTask(){
    public void run(){
      closeOldConnection();
    }
  }
,1,closeDelay);
}
 

Example 26

From project DirectMemory, under directory /DirectMemory-Cache/src/main/java/org/apache/directmemory/cache/.

Source file: CacheServiceImpl.java

  31 
vote

@Override public void scheduleDisposalEvery(long l){
  timer.schedule(new TimerTask(){
    public void run(){
      logger.info("begin scheduled disposal");
      collectExpired();
      collectLFU();
      logger.info("scheduled disposal complete");
    }
  }
,l,l);
  logger.info("disposal scheduled every {} milliseconds",l);
}
 

Example 27

From project dmix, under directory /MPDroid/src/com/namelessdev/mpdroid/.

Source file: MPDApplication.java

  31 
vote

private void startDisconnectSheduler(){
  disconnectSheduler.schedule(new TimerTask(){
    @Override public void run(){
      Log.w(TAG,"Disconnecting (" + DISCONNECT_TIMER + " ms timeout)");
      oMPDAsyncHelper.disconnect();
    }
  }
,DISCONNECT_TIMER);
}
 

Example 28

From project droid-fu, under directory /src/main/java/com/google/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 29

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/stats/.

Source file: Stats.java

  31 
vote

private void startTimer(long interval){
  stopTimer();
  if (interval > 0) {
    sendTimer=new Timer();
    long delay=Math.max(0,interval - timeSinceLastSendTry());
    sendTimer.schedule(new TimerTask(){
      @Override public void run(){
        send();
      }
    }
,delay,interval);
  }
}
 

Example 30

From project FlipDroid, under directory /web-image-view/src/main/java/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 31

From project generic-store-for-android, under directory /src/com/google/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 32

From project gxa, under directory /atlas-analytics/src/main/java/uk/ac/ebi/gxa/R/.

Source file: BiocepAtlasRFactory.java

  31 
vote

private static void waitFor(long milliseconds){
  final CountDownLatch latch=new CountDownLatch(1);
  new Timer().schedule(new TimerTask(){
    @Override public void run(){
      latch.countDown();
    }
  }
,milliseconds);
  try {
    latch.await();
  }
 catch (  InterruptedException e) {
  }
}
 

Example 33

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/jerklib/.

Source file: ConnectionManager.java

  31 
vote

/** 
 * Starts a Thread for IO/Parsing/Checking-Making Connections Start another Thread for relaying events
 */
void startMainLoop(){
  dispatchTimer=new Timer();
  loopTimer=new Timer();
  TimerTask dispatchTask=new TimerTask(){
    public void run(){
      relayEvents();
      notifyWriteListeners();
    }
  }
;
  TimerTask loopTask=new TimerTask(){
    public void run(){
      makeConnections();
      doNetworkIO();
      parseEvents();
      checkServerConnections();
    }
  }
;
  loopTimer.schedule(loopTask,0,200);
  dispatchTimer.schedule(dispatchTask,0,200);
}
 

Example 34

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/metrics/spi/.

Source file: AbstractMetricsContext.java

  31 
vote

/** 
 * Starts timer if it is not already started
 */
private synchronized void startTimer(){
  if (timer == null) {
    timer=new Timer("Timer thread for monitoring " + getContextName(),true);
    TimerTask task=new TimerTask(){
      public void run(){
        try {
          timerEvent();
        }
 catch (        IOException ioe) {
          ioe.printStackTrace();
        }
      }
    }
;
    long millis=period * 1000;
    timer.scheduleAtFixedRate(task,millis,millis);
  }
}
 

Example 35

From project ib-ruby, under directory /misc/IBController 2-9-0/src/ibcontroller/.

Source file: IBController.java

  31 
vote

private static void startShutdownTimerIfRequired(){
  Date shutdownTime=getShutdownTime();
  if (!(shutdownTime == null)) {
    Utils.logToConsole(((_GatewayOnly) ? "Gateway" : "TWS") + " will be shut down at " + (new SimpleDateFormat("yyyy/MM/dd HH:mm")).format(shutdownTime));
    _Timer.schedule(new TimerTask(){
      public void run(){
        GuiExecutor.instance().execute(new StopTask(_GatewayOnly,null));
        _Timer.cancel();
      }
    }
,shutdownTime);
  }
}
 

Example 36

From project ioke, under directory /src/ikj/main/com/google/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 37

From project java-exec, under directory /src/com/thoughtworks/studios/javaexec/.

Source file: ProcessWatcher.java

  31 
vote

public void start(){
  timer=new Timer();
  timer.schedule(new TimerTask(){
    public void run(){
      process.destroy();
      timedOut=true;
    }
  }
,timeout);
}
 

Example 38

From project JDE-Samples, under directory /com/rim/samples/device/location/gpsdemoadvanced/.

Source file: CoreGPSDiagnosticScreen.java

  31 
vote

private void setupPDE(){
  final String pdeIPText=_pdeIPField.getText();
  final String pdePortText=_pdePortField.getText();
  if (pdeIPText.length() > 0) {
    if (!_isVerizonField.getChecked()) {
      log("Using PDE: " + pdeIPText + ":"+ pdePortText);
      final boolean setPDESuccess=GPSSettings.setPDEInfo(pdeIPText,Integer.parseInt(pdePortText));
      if (setPDESuccess) {
        _PDESet=true;
        log("setPDEInfo() successful");
      }
    }
 else {
      log("Using VZ Credentials: " + ";" + pdeIPText + ";"+ pdePortText);
      GPSSettings.setPDEInfo(";" + pdeIPText + ";"+ pdePortText,0);
      final Timer timer=new Timer();
      final TimerTask task=new TimerTask(){
        /** 
 * @see java.util.TimerTask#run()
 */
        public void run(){
          clearVerizonCredential();
          setupPDE();
          resetProvider();
          setupProvider();
        }
      }
;
      final long period=1000 * 60 * 60* 12 - 60000;
      long date=new Date().getTime();
      date=date + period;
      timer.scheduleAtFixedRate(task,period,date);
      _PDESet=true;
    }
  }
}
 

Example 39

From project MimeUtil, under directory /src/main/java/eu/medsea/mimeutil/detector/.

Source file: OpendesktopMimeDetector.java

  31 
vote

private void init(final String mimeCacheFile){
  String cacheFile=mimeCacheFile;
  if (!new File(cacheFile).exists()) {
    cacheFile=internalMimeCacheFile;
  }
  FileChannel rCh=null;
  try {
    RandomAccessFile raf=null;
    raf=new RandomAccessFile(cacheFile,"r");
    rCh=(raf).getChannel();
    content=rCh.map(FileChannel.MapMode.READ_ONLY,0,rCh.size());
    initMimeTypes();
    if (log.isDebugEnabled()) {
      log.debug("Registering a FileWatcher for [" + cacheFile + "]");
    }
    TimerTask task=new FileWatcher(new File(cacheFile)){
      protected void onChange(      File file){
        initMimeTypes();
      }
    }
;
    timer=new Timer();
    timer.schedule(task,new Date(),10000);
  }
 catch (  Exception e) {
    throw new MimeException(e);
  }
 finally {
    if (rCh != null) {
      try {
        rCh.close();
      }
 catch (      Exception e) {
        log.error(e.getLocalizedMessage(),e);
      }
    }
  }
}
 

Example 40

From project movsim, under directory /viewer/src/main/java/org/movsim/viewer/graphics/.

Source file: VehicleTipWindow.java

  31 
vote

void start(long id){
  timedPopupId=id;
  timer.schedule(new TimerTask(){
    @Override public void run(){
      if (timedPopupId == currentPopupId) {
        setVisible(false);
        VehicleTipWindow.this.trafficCanvas.vehiclePopup=null;
      }
    }
  }
,popupTime);
}
 

Example 41

From project Opal, under directory /discontinued/opal-geo/src/main/java/com/lyndir/lhunath/opal/gui/.

Source file: Splash.java

  31 
vote

/** 
 * Fade the initial image over into the final image.
 * @param duration The duration over which to fade.
 */
public void fade(final int duration){
  startTime=System.currentTimeMillis();
  endTime=startTime + duration;
  new Timer("Splash Fade Timer",true).scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      repaint();
    }
  }
,0,Math.max(1,(endTime - startTime) / 1000));
}
 

Example 42

From project org.openscada.atlantis, under directory /org.openscada.da.server.exec/src/org/openscada/da/server/exec/command/.

Source file: CommandQueueImpl.java

  31 
vote

public void start(final Hive hive,final FolderCommon baseFolder){
  for (  final Entry entry : this.commands) {
    entry.getCommand().register(hive,baseFolder);
  }
  this.timer=new Timer(true);
  this.timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      runOnce();
    }
  }
,new Date(),this.loopDelay);
}
 

Example 43

From project orientdb, under directory /server/src/main/java/com/orientechnologies/orient/server/handler/distributed/.

Source file: ODistributedServerDiscoverySignaler.java

  31 
vote

private void startTimeoutPresenceTask(){
  Orient.getTimer().schedule(new TimerTask(){
    @Override public void run(){
      try {
        sendShutdown();
        manager.becameLeader(forceLeadership);
      }
 catch (      Exception e) {
      }
    }
  }
,manager.networkTimeoutLeader);
}
 

Example 44

From project Path-Computation-Element-Emulator, under directory /PCEE/src/com/pcee/architecture/sessionmodule/statemachine/.

Source file: StateMachineImpl.java

  31 
vote

/** 
 * Connect
 */
private void startConnectTimer(){
  localDebugger("Entering: startConnectTimer()");
  localLogger("Starting Connect Timer");
  connectTimerRunning=true;
  connectTimerTask=new TimerTask(){
    public void run(){
      localLogger("ConnectTimer Expired");
      checkPendingStatus();
    }
  }
;
  stateTimer.schedule(connectTimerTask,connect * 1000);
}
 

Example 45

From project PermissionsEx, under directory /src/main/java/ru/tehkode/permissions/.

Source file: PermissionEntity.java

  31 
vote

/** 
 * Adds timed permission to specified world in seconds
 * @param permission
 * @param world
 * @param lifeTime Lifetime of permission in seconds. 0 for transient permission (world disappear only after server reload)
 */
public void addTimedPermission(final String permission,String world,int lifeTime){
  if (world == null) {
    world="";
  }
  if (!this.timedPermissions.containsKey(world)) {
    this.timedPermissions.put(world,new LinkedList<String>());
  }
  this.timedPermissions.get(world).add(permission);
  final String finalWorld=world;
  if (lifeTime > 0) {
    TimerTask task=new TimerTask(){
      @Override public void run(){
        removeTimedPermission(permission,finalWorld);
      }
    }
;
    this.manager.registerTask(task,lifeTime);
    this.timedPermissionsTime.put(world + ":" + permission,(System.currentTimeMillis() / 1000L) + lifeTime);
  }
  this.callEvent(PermissionEntityEvent.Action.PERMISSIONS_CHANGED);
}
 

Example 46

From project platform_external_guava, under directory /src/com/google/common/collect/.

Source file: MapMaker.java

  31 
vote

void scheduleRemoval(K key,V value){
  final WeakReference<K> keyReference=new WeakReference<K>(key);
  final WeakReference<V> valueReference=new WeakReference<V>(value);
  ExpirationTimer.instance.schedule(new TimerTask(){
    @Override public void run(){
      K key=keyReference.get();
      if (key != null) {
        map.remove(key,valueReference.get());
      }
    }
  }
,TimeUnit.NANOSECONDS.toMillis(expirationNanos));
}
 

Example 47

From project pomodoro4nb, under directory /src/org/matveev/pomodoro4nb/.

Source file: Notificator.java

  31 
vote

public static void showNotificationBalloon(String key,ActionListener listener){
  final Notification notification=NotificationDisplayer.getDefault().notify(getMessage(key + ".title"),Resources.createIcon(getMessage(key + ".iconName")),getMessage(key + ".text"),listener);
  final Timer removeNotificationTimer=new Timer();
  removeNotificationTimer.schedule(new TimerTask(){
    @Override public void run(){
      notification.clear();
    }
  }
,DEFAULT_NOTIFACTION_DELAY);
}
 

Example 48

From project pos_1, under directory /jetty/contrib/cometd/bayeux/src/main/java/org/mortbay/cometd/continuation/.

Source file: ContinuationBayeux.java

  31 
vote

@Override protected void initialize(ServletContext context){
  super.initialize(context);
  _tick=new Timer("ContinuationBayeux-" + __id++,true);
  _timeout=new Timeout();
  _timeout.setDuration(getMaxInterval());
  _tick.schedule(new TimerTask(){
    @Override public void run(){
      _now=System.currentTimeMillis();
      _timeout.tick(_now);
    }
  }
,500L,500L);
}
 

Example 49

From project riot, under directory /common/src/org/riotfamily/common/log4j/.

Source file: SmartSmtpAppender.java

  31 
vote

private synchronized void schedule(long delay){
  if (!reportScheduled) {
    reportScheduled=true;
    timer.schedule(new TimerTask(){
      public void run(){
        send();
      }
    }
,delay);
  }
}
 

Example 50

From project rj-core, under directory /de.walware.rj.server/src/de/walware/rj/server/.

Source file: RMIServerControl.java

  31 
vote

void scheduleCleanup(){
  new Timer().schedule(new TimerTask(){
    @Override public void run(){
      checkCleanup();
    }
  }
,2000);
}
 

Example 51

From project subsonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.

Source file: MediaScannerService.java

  31 
vote

/** 
 * Schedule background execution of media library scanning.
 */
public synchronized void schedule(){
  if (timer != null) {
    timer.cancel();
  }
  timer=new Timer(true);
  TimerTask task=new TimerTask(){
    @Override public void run(){
      scanLibrary();
    }
  }
;
  long daysBetween=settingsService.getIndexCreationInterval();
  int hour=settingsService.getIndexCreationHour();
  if (daysBetween == -1) {
    LOG.info("Automatic media scanning disabled.");
    return;
  }
  Date now=new Date();
  Calendar cal=Calendar.getInstance();
  cal.setTime(now);
  cal.set(Calendar.HOUR_OF_DAY,hour);
  cal.set(Calendar.MINUTE,0);
  cal.set(Calendar.SECOND,0);
  if (cal.getTime().before(now)) {
    cal.add(Calendar.DATE,1);
  }
  Date firstTime=cal.getTime();
  long period=daysBetween * 24L * 3600L* 1000L;
  timer.schedule(task,firstTime,period);
  LOG.info("Automatic media library scanning scheduled to run every " + daysBetween + " day(s), starting at "+ firstTime);
  if (settingsService.getLastScanned() == null) {
    LOG.info("Media library never scanned. Doing it now.");
    scanLibrary();
  }
}
 

Example 52

From project subsonic_1, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.

Source file: MediaScannerService.java

  31 
vote

/** 
 * Schedule background execution of media library scanning.
 */
public synchronized void schedule(){
  if (timer != null) {
    timer.cancel();
  }
  timer=new Timer(true);
  TimerTask task=new TimerTask(){
    @Override public void run(){
      scanLibrary();
    }
  }
;
  long daysBetween=settingsService.getIndexCreationInterval();
  int hour=settingsService.getIndexCreationHour();
  if (daysBetween == -1) {
    LOG.info("Automatic media scanning disabled.");
    return;
  }
  Date now=new Date();
  Calendar cal=Calendar.getInstance();
  cal.setTime(now);
  cal.set(Calendar.HOUR_OF_DAY,hour);
  cal.set(Calendar.MINUTE,0);
  cal.set(Calendar.SECOND,0);
  if (cal.getTime().before(now)) {
    cal.add(Calendar.DATE,1);
  }
  Date firstTime=cal.getTime();
  long period=daysBetween * 24L * 3600L* 1000L;
  timer.schedule(task,firstTime,period);
  LOG.info("Automatic media library scanning scheduled to run every " + daysBetween + " day(s), starting at "+ firstTime);
  if (settingsService.getLastScanned() == null) {
    LOG.info("Media library never scanned. Doing it now.");
    scanLibrary();
  }
}
 

Example 53

From project subsonic_2, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.

Source file: SearchService.java

  31 
vote

/** 
 * Schedule background execution of index creation.
 */
public synchronized void schedule(){
  if (timer != null) {
    timer.cancel();
  }
  timer=new Timer(true);
  TimerTask task=new TimerTask(){
    @Override public void run(){
      createIndex();
    }
  }
;
  long daysBetween=settingsService.getIndexCreationInterval();
  int hour=settingsService.getIndexCreationHour();
  if (daysBetween == -1) {
    LOG.info("Automatic index creation disabled.");
    return;
  }
  Date now=new Date();
  Calendar cal=Calendar.getInstance();
  cal.setTime(now);
  cal.set(Calendar.HOUR_OF_DAY,hour);
  cal.set(Calendar.MINUTE,0);
  cal.set(Calendar.SECOND,0);
  if (cal.getTime().before(now)) {
    cal.add(Calendar.DATE,1);
  }
  Date firstTime=cal.getTime();
  long period=daysBetween * 24L * 3600L* 1000L;
  timer.schedule(task,firstTime,period);
  LOG.info("Automatic index creation scheduled to run every " + daysBetween + " day(s), starting at "+ firstTime);
  if (!isIndexCreated()) {
    LOG.info("Search index not found on disk. Creating it.");
    createIndex();
  }
}
 

Example 54

From project summer, under directory /samples/java/src/main/java/com/asual/summer/sample/websocket/.

Source file: Clock.java

  31 
vote

public Clock(){
  timer.schedule(new TimerTask(){
    public void run(){
      date.setTime(System.currentTimeMillis());
      topic.broadcast(dateFormat.format(date));
    }
  }
,new Date(),1000);
}
 

Example 55

From project Supersonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.

Source file: MediaScannerService.java

  31 
vote

/** 
 * Schedule background execution of media library scanning.
 */
public synchronized void schedule(){
  if (timer != null) {
    timer.cancel();
  }
  timer=new Timer(true);
  TimerTask task=new TimerTask(){
    @Override public void run(){
      scanLibrary();
    }
  }
;
  long daysBetween=settingsService.getIndexCreationInterval();
  int hour=settingsService.getIndexCreationHour();
  if (daysBetween == -1) {
    LOG.info("Automatic media scanning disabled.");
    return;
  }
  Date now=new Date();
  Calendar cal=Calendar.getInstance();
  cal.setTime(now);
  cal.set(Calendar.HOUR_OF_DAY,hour);
  cal.set(Calendar.MINUTE,0);
  cal.set(Calendar.SECOND,0);
  if (cal.getTime().before(now)) {
    cal.add(Calendar.DATE,1);
  }
  Date firstTime=cal.getTime();
  long period=daysBetween * 24L * 3600L* 1000L;
  timer.schedule(task,firstTime,period);
  LOG.info("Automatic media library scanning scheduled to run every " + daysBetween + " day(s), starting at "+ firstTime);
  if (settingsService.getLastScanned() == null) {
    LOG.info("Media library never scanned. Doing it now.");
    scanLibrary();
  }
}
 

Example 56

From project SWOWS, under directory /swows/src/main/java/org/swows/time/.

Source file: SystemTime.java

  31 
vote

public DynamicGraph getGraph(){
  timeGraph=new DynamicGraphFromGraph(GraphFactory.createGraphMem());
  currTriple=tripleFromTime();
  timeGraph.add(currTriple);
  Timer updateTimer=new Timer();
  updateTimer.schedule(new TimerTask(){
    @Override public void run(){
      RunnableContextFactory.getDefaultRunnableContext().run(SystemTime.this);
    }
  }
,0,updatePeriod);
  return timeGraph;
}
 

Example 57

From project titanium_modules, under directory /beintoosdk/mobile/android/src/com/beintoo/beintoosdkutility/.

Source file: ErrorDisplayer.java

  31 
vote

public static void showConnectionErrorOnThread(String Message,final Context ctx,Exception e){
  Looper.prepare();
  final Looper tLoop=Looper.myLooper();
  showConnectionError(Message,ctx,e);
  final Timer t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      tLoop.quit();
      t.cancel();
    }
  }
,6000);
  Looper.loop();
}
 

Example 58

From project Vega, under directory /platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/.

Source file: Workspace.java

  31 
vote

private TimerTask createBackgroundCommitTask(final ObjectContainer db){
  return new TimerTask(){
    @Override public void run(){
      if (!db.ext().isClosed()) {
        db.commit();
      }
    }
  }
;
}
 

Example 59

From project Android_1, under directory /Livewallpaper/switch_animation/src/com/novoda/wallpaper/.

Source file: AnimSwitchWallPaper.java

  30 
vote

@Override public void onTouchEvent(MotionEvent event){
  if (event.getAction() == MotionEvent.ACTION_DOWN) {
    mDragEventInProgress=true;
    mDragEventStartX=event.getX();
  }
  if (event.getAction() == MotionEvent.ACTION_UP) {
    boolean draggedLotsRight=(mDragEventStartX - event.getX()) >= 160;
    boolean draggedLotsLeft=(event.getX() - mDragEventStartX) >= 160;
    Log.v(TAG,"X:[" + event.getX() + "+] - dragStart["+ mDragEventStartX+ "] ="+ (event.getX() - mDragEventStartX));
    if ((mDragEventStartX > 150) && draggedLotsRight) {
      takingACorner=true;
      currentDirection=DRIVING_RIGHT;
      Log.d(TAG,"Driving animation started Right >");
      new Timer().schedule(new TimerTask(){
        @Override public void run(){
          takingACorner=false;
          picIdx=0;
        }
      }
,1000);
    }
    if ((mDragEventStartX < 150) && draggedLotsLeft) {
      takingACorner=true;
      currentDirection=DRIVING_LEFT;
      Log.d(TAG,"Driving animation started < Left");
      new Timer().schedule(new TimerTask(){
        @Override public void run(){
          takingACorner=false;
          picIdx=0;
        }
      }
,1000);
    }
    mDragEventInProgress=false;
    mDragEventStartX=0;
  }
  super.onTouchEvent(event);
}
 

Example 60

From project bam, under directory /modules/active-queries/active-collection/src/main/java/org/overlord/bam/active/collection/.

Source file: ActiveCollectionSource.java

  30 
vote

/** 
 * This method initializes the active collection source.
 * @throws Exception Failed to initialize source
 */
public void init() throws Exception {
  preInit();
  if (_listeners.size() > 0) {
    if (_activeCollection == null) {
      throw new Exception("Active collection has not been associated with the '" + getName() + "' source");
    }
    for (    AbstractActiveChangeListener l : _listeners) {
      if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("Initialize active collection '" + getName() + "' with listener from source: "+ l);
      }
      l.init();
      _activeCollection.addActiveChangeListener(l);
    }
  }
  if (_groupBy != null) {
    _groupByExpression=MVEL.compileExpression(_groupBy);
    if (_aggregationDuration > 0) {
      _aggregator=new Aggregator();
    }
  }
  if (_scheduledScriptExpression != null && _scheduledInterval > 0) {
    _scheduledTimer=new java.util.Timer();
    _scheduledTimer.scheduleAtFixedRate(new TimerTask(){
      public void run(){
        java.util.Map<String,Object> vars=new java.util.HashMap<String,Object>();
        vars.put("acs",ActiveCollectionSource.this);
        vars.put("variables",_variables);
        if (LOG.isLoggable(Level.FINE)) {
          LOG.fine("Call scheduled script on '" + getName() + "' with variables: "+ _variables);
        }
synchronized (ActiveCollectionSource.this) {
          MVEL.executeExpression(_scheduledScriptExpression,vars);
        }
      }
    }
,0,_scheduledInterval);
  }
}
 

Example 61

From project BioMAV, under directory /ParrotControl/JavaDroneControl/src/nl/ru/ai/projects/parrot/dronecontrol/javadronecontrol/test/.

Source file: Test01.java

  30 
vote

public Test01(){
  super("Test vision frame");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH,VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT);
  Timer timer=new Timer();
  timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      byte[] imageData=drone.getFrontCameraImage();
      System.out.println("Front camera timestamp: " + drone.getFrontCameraTimeStamp());
      if (imageData != null) {
        WritableRaster raster=Raster.createBandedRaster(DataBuffer.TYPE_BYTE,VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH,VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT,3,new Point(0,0));
        raster.setDataElements(0,0,VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH,VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT,imageData);
        image.setData(raster);
      }
      repaint();
    }
  }
,200,200);
}
 

Example 62

From project chililog-server, under directory /src/main/java/org/chililog/server/.

Source file: App.java

  30 
vote

/** 
 * Polls for the shutdown file - and shuts down if one is found
 */
static void addShutdownPoller(){
  final File file=new File(".",STOP_ME_FILENAME);
  if (file.exists()) {
    file.delete();
  }
  final Timer timer=new Timer("ChiliLog Server Shutdown Timer",true);
  timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      if (file.exists()) {
        try {
          stop(null);
          timer.cancel();
        }
 catch (        Exception e) {
          _logger.error(e,"Shutdown error: " + e.getMessage());
        }
 finally {
          Runtime.getRuntime().exit(0);
        }
      }
    }
  }
,1000,1000);
}
 

Example 63

From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/session/.

Source file: SessionManager.java

  30 
vote

public void setScavengePeriod(int seconds){
  if (seconds == 0)   seconds=60;
  long oldPeriods=_scavengePeriodMs;
  long period=seconds * 1000l;
  if (period > 60000)   period=60000;
  if (period < 1000)   period=1000;
  _scavengePeriodMs=period;
  if (_timer != null && (period != oldPeriods || _task == null)) {
synchronized (this) {
      if (_task != null)       _task.cancel();
      _task=new TimerTask(){
        @Override public void run(){
          scavenge();
        }
      }
;
      _timer.schedule(_task,_scavengePeriodMs,_scavengePeriodMs);
    }
  }
}
 

Example 64

From project cometd, under directory /cometd-java/cometd-java-server/src/main/java/org/cometd/server/.

Source file: BayeuxServerImpl.java

  30 
vote

@Override protected void doStart() throws Exception {
  super.doStart();
  _logLevel=OFF_LOG_LEVEL;
  Object logLevelValue=getOption(LOG_LEVEL);
  if (logLevelValue != null)   _logLevel=Integer.parseInt(String.valueOf(logLevelValue));
  if (_logLevel >= CONFIG_LOG_LEVEL) {
    for (    Map.Entry<String,Object> entry : getOptions().entrySet())     _logger.info("{}={}",entry.getKey(),entry.getValue());
  }
  initializeMetaChannels();
  initializeJSONContext();
  initializeDefaultTransports();
  List<String> allowedTransportNames=getAllowedTransports();
  if (allowedTransportNames.isEmpty())   throw new IllegalStateException("No allowed transport names are configured, there must be at least one");
  for (  String allowedTransportName : allowedTransportNames) {
    ServerTransport allowedTransport=getTransport(allowedTransportName);
    if (allowedTransport instanceof AbstractServerTransport)     ((AbstractServerTransport)allowedTransport).init();
  }
  _timer=new Timer("BayeuxServer@" + hashCode(),true);
  long tick_interval=getOption("tickIntervalMs",97);
  if (tick_interval > 0) {
    _timer.schedule(new TimerTask(){
      @Override public void run(){
        _timeout.tick(System.currentTimeMillis());
      }
    }
,tick_interval,tick_interval);
  }
  long sweep_interval=getOption("sweepIntervalMs",997);
  if (sweep_interval > 0) {
    _timer.schedule(new TimerTask(){
      @Override public void run(){
        sweep();
      }
    }
,sweep_interval,sweep_interval);
  }
}
 

Example 65

From project components, under directory /bpel/src/main/java/org/switchyard/component/bpel/riftsaw/.

Source file: RiftsawBPELExchangeHandler.java

  30 
vote

/** 
 * {@inheritDoc}
 */
public void stop(){
  if (LOG.isDebugEnabled()) {
    LOG.debug("STOP: " + _serviceName);
  }
  _undeployed.add(_serviceName);
  if (_undeployDelay > 0) {
    _timer.schedule(new TimerTask(){
      public void run(){
        undeploy();
      }
    }
,_undeployDelay);
  }
 else {
    undeploy();
  }
  _serviceRefToCompositeMap.remove(_serviceName);
}
 

Example 66

From project connectbot, under directory /src/sk/vx/connectbot/service/.

Source file: TerminalManager.java

  30 
vote

public void addKey(PubkeyBean pubkey,Object trileadKey,boolean force){
  if (!savingKeys && !force)   return;
  removeKey(pubkey.getNickname());
  byte[] sshPubKey=PubkeyUtils.extractOpenSSHPublic(trileadKey);
  KeyHolder keyHolder=new KeyHolder();
  keyHolder.bean=pubkey;
  keyHolder.trileadKey=trileadKey;
  keyHolder.openSSHPubkey=sshPubKey;
  loadedKeypairs.put(pubkey.getNickname(),keyHolder);
  if (pubkey.getLifetime() > 0) {
    final String nickname=pubkey.getNickname();
    pubkeyTimer.schedule(new TimerTask(){
      @Override public void run(){
        Log.d(TAG,"Unloading from memory key: " + nickname);
        removeKey(nickname);
      }
    }
,pubkey.getLifetime() * 1000);
  }
  Log.d(TAG,String.format("Added key '%s' to in-memory cache",pubkey.getNickname()));
}
 

Example 67

From project craftbook, under directory /oldsrc/commonrefactor/com/sk89q/craftbook/mech/.

Source file: MinecartDecayWatcher.java

  30 
vote

/** 
 * Construct the object and start the timer.
 * @param delay maximum age of empty minecarts in seconds
 */
public MinecartDecayWatcher(int delay){
  this.delay=delay * 1000;
  timer.scheduleAtFixedRate(new TimerTask(){
    /** 
 * Runs the check.
 */
    @Override public void run(){
      WorldInterface[] worlds=minecarts.keySet().toArray(new WorldInterface[0]);
      for (      final WorldInterface world : worlds)       world.enqueAction(new Runnable(){
        /** 
 * Performs the check.
 */
        @Override public void run(){
          performCheck(world);
        }
      }
);
    }
  }
,0,3000);
}
 

Example 68

From project data-bus, under directory /databus-worker/src/test/java/com/inmobi/databus/.

Source file: DatabusTest.java

  30 
vote

private void testDatabus(String filename) throws Exception {
  DatabusConfigParser configParser=new DatabusConfigParser(filename);
  DatabusConfig config=configParser.getConfig();
  Set<String> clustersToProcess=new HashSet<String>();
  FileSystem fs=FileSystem.getLocal(new Configuration());
  for (  Map.Entry<String,Cluster> cluster : config.getClusters().entrySet()) {
    String jobTracker=super.CreateJobConf().get("mapred.job.tracker");
    cluster.getValue().getHadoopConf().set("mapred.job.tracker",jobTracker);
  }
  for (  Map.Entry<String,SourceStream> sstream : config.getSourceStreams().entrySet()) {
    clustersToProcess.addAll(sstream.getValue().getSourceClusters());
  }
  testService=new DatabusServiceTest(config,clustersToProcess);
  Timer timer=new Timer();
  Calendar calendar=new GregorianCalendar();
  calendar.add(Calendar.MINUTE,5);
  timer.schedule(new TimerTask(){
    public void run(){
      try {
        LOG.info("Stopping Databus Test Service");
        testService.stop();
        LOG.info("Done stopping Databus Test Service");
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
,calendar.getTime());
  LOG.info("Starting Databus Test Service");
  testService.startDatabus();
  for (  Map.Entry<String,Cluster> cluster : config.getClusters().entrySet()) {
    fs.delete(new Path(cluster.getValue().getRootDir()),true);
  }
  LOG.info("Done with Databus Test Service");
}
 

Example 69

From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/ui/internal/wizards/.

Source file: ImportTraceWizardPage1.java

  30 
vote

private void schedule(){
  long time=System.currentTimeMillis();
synchronized (timer) {
    if (state == SCHEDULED && task != null) {
      task.cancel();
      state=WAITING;
    }
    task=new TimerTask(){
      @Override public void run(){
synchronized (timer) {
          if (state != SCHEDULED)           return;
          state=RUNNING;
          getShell().getDisplay().syncExec(FileValidator.this);
          state=WAITING;
        }
      }
    }
;
    state=SCHEDULED;
    timer.schedule(task,new Date(time + 1000));
  }
}
 

Example 70

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/location/.

Source file: UpdateLocation.java

  30 
vote

@Override public void onCreate(){
  DBHelper dbh=new DBHelper(this);
  friendsList=dbh.getPublicKeyPrints();
  idToSharedKeyMap=dbh.getPublicKeyPrintSharedSecretMap();
  mClient=new ClientClass(IP_ADDRESS,8080);
  if (!mClient.connectMe()) {
    for (int i=0; i < 10; i++) {
      try {
        Thread.sleep(5000);
      }
 catch (      InterruptedException e) {
        e.printStackTrace();
      }
      if (mClient.connectMe())       break;
    }
    stopSelf();
  }
  myID=dbh.getPublicKeyPrint();
  for (int i=0; i < 3; i++)   gridLocation[i]=BigInteger.valueOf(0);
  myLocator=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
  myLocator.requestLocationUpdates(LocationManager.GPS_PROVIDER,minTimeMillisec,minDistanceMeters,locationUpdater);
  curDate=new Date();
  Long seed=new Long(curDate.getTime());
  byte[] seed_bytes=new byte[8];
  for (int i=0; i < 8; i++) {
    seed_bytes[7 - i]=(byte)(seed >>> (i * 8));
  }
  SecureRandom randGenerator=new SecureRandom(seed_bytes);
  serverKey=new byte[16];
  randGenerator.nextBytes(serverKey);
  mClient.sendSharedKey(myID,serverKey);
  sendTimer.schedule(new TimerTask(){
    public void run(){
      sendLocation();
    }
  }
,0,INTERVAL);
}
 

Example 71

From project embedmongo.flapdoodle.de, under directory /src/main/java/de/flapdoodle/embedmongo/.

Source file: MongodProcess.java

  30 
vote

/** 
 * It may happen in tests, that the process is currently using some files in the temp directory, e.g. journal files (journal/j._0) and got killed at that time, so it takes a bit longer to kill the process. So we just wait for a second (in 10 ms steps) that the process got really killed.
 */
private void waitForProcessGotKilled(){
  final Timer timer=new Timer();
  timer.scheduleAtFixedRate(new TimerTask(){
    public void run(){
      try {
        _process.waitFor();
      }
 catch (      InterruptedException e) {
        _logger.severe(e.getMessage());
      }
 finally {
        _processKilled=true;
        timer.cancel();
      }
    }
  }
,0,10);
  int countDown=100;
  while (!_processKilled && (countDown-- > 0))   try {
    Thread.sleep(10);
  }
 catch (  InterruptedException e) {
    _logger.severe(e.getMessage());
  }
  if (!_processKilled) {
    timer.cancel();
    throw new IllegalStateException("Couldn't kill mongod process!");
  }
}
 

Example 72

From project FileExplorer, under directory /src/net/micode/fileexplorer/.

Source file: CategoryBar.java

  30 
vote

synchronized public void startAnimation(){
  if (timer != null) {
    return;
  }
  Log.v(LOG_TAG,"startAnimation");
  for (  Category c : categories) {
    c.tmpValue=0;
    c.aniStep=c.value / ANI_TOTAL_FRAMES;
  }
  timer=new Timer();
  timer.scheduleAtFixedRate(new TimerTask(){
    public void run(){
      stepAnimation();
    }
  }
,0,ANI_PERIOD);
}
 

Example 73

From project formic, under directory /src/java/org/formic/wizard/form/gui/binding/.

Source file: TextComponentBinding.java

  30 
vote

private void textUpdated(final DocumentEvent e){
  if (timer != null) {
    timer.cancel();
  }
  timer=new Timer();
  timer.schedule(new TimerTask(){
    public void run(){
      try {
        Document document=e.getDocument();
        String value=document.getText(0,document.getLength());
        boolean valid=ValidationUtils.validate(component,value);
        form.setValue(TextComponentBinding.this,component,value,valid);
        timer.cancel();
      }
 catch (      Exception ex) {
        Installer.getProject().log("Error on text update",ex,Project.MSG_DEBUG);
      }
    }
  }
,200);
}
 

Example 74

From project groovejaar, under directory /src/groovejaar/.

Source file: GrooveJaar.java

  30 
vote

public static void initTimer(final int streamServerID,final String streamKey,final String id){
  timer=new Timer();
  timer.schedule(new TimerTask(){
    public void run(){
      try {
        JGroovex.markStreamKeyOver30Seconds(0,streamServerID,streamKey,id);
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
      timer.cancel();
    }
  }
,30 * 1000);
}
 

Example 75

From project guj.com.br, under directory /src/br/com/caelum/guj/feeds/.

Source file: Agregator.java

  30 
vote

private void init(){
  long interval=Config.getIntvalue(this.intervalKey) * 1000 * 60;
  Timer infoqTimer=new Timer(true);
  infoqTimer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      try {
        List<ItemIF> newFeeds=new ArrayList<ItemIF>(FeedReader.read(Config.getValue(Agregator.this.feedUrl)));
        int max=Config.getIntvalue(Agregator.this.maxItemsKey);
        if (newFeeds.size() > max) {
          newFeeds=newFeeds.subList(0,max);
        }
        if (!newFeeds.isEmpty()) {
          Agregator.this.items=newFeeds;
        }
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
,new Date(),interval);
}
 

Example 76

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/framework/.

Source file: CheckpointService.java

  30 
vote

/** 
 * Setup checkpointTask according to current interval. (An already-scheduled task, if any, is canceled.)
 */
protected synchronized void setupCheckpointTask(){
  if (checkpointTask != null) {
    checkpointTask.cancel();
  }
  if (!isRunning) {
    return;
  }
  long periodMs=getCheckpointIntervalMinutes() * (60L * 1000L);
  if (periodMs <= 0) {
    return;
  }
  checkpointTask=new TimerTask(){
    public void run(){
      if (isCheckpointing()) {
        LOGGER.info("CheckpointTimerThread skipping checkpoint, " + "already checkpointing: State: " + controller.getState());
        return;
      }
      LOGGER.info("TimerThread request checkpoint");
      requestCrawlCheckpoint();
    }
  }
;
  this.timer.schedule(checkpointTask,periodMs,periodMs);
  LOGGER.info("Installed Checkpoint TimerTask to checkpoint every " + periodMs + " milliseconds.");
}
 

Example 77

From project huiswerk, under directory /print/zxing-1.6/android/src/com/google/zxing/client/android/wifi/.

Source file: Killer.java

  30 
vote

public void run(){
  final Handler handler=new Handler();
  Timer t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      handler.post(new Runnable(){
        public void run(){
          launchIntent(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com/")));
        }
      }
);
    }
  }
,DELAY_MS);
}
 

Example 78

From project k-9, under directory /src/com/fsck/k9/helper/power/.

Source file: TracingPowerManager.java

  30 
vote

private void raiseNotification(){
  if (timer != null) {
synchronized (timer) {
      if (timerTask != null) {
        timerTask.cancel();
        timerTask=null;
      }
      timerTask=new TimerTask(){
        @Override public void run(){
          if (startTime != null) {
            Long endTime=System.currentTimeMillis();
            Log.i(K9.LOG_TAG,"TracingWakeLock for tag " + tag + " / id "+ id+ ": has been active for "+ (endTime - startTime)+ " ms, timeout = "+ timeout+ " ms");
          }
 else {
            Log.i(K9.LOG_TAG,"TracingWakeLock for tag " + tag + " / id "+ id+ ": still active, timeout = "+ timeout+ " ms");
          }
        }
      }
;
      timer.schedule(timerTask,1000,1000);
    }
  }
}
 

Example 79

From project LanguageSpecCreator, under directory /src/liber/edit/server/.

Source file: LiberServletImpl.java

  30 
vote

/** 
 * Constructor. Initialises the servlet, reading the ontology model from static files and creating a cleaner thread that removes obsolete sessions.
 */
public LiberServletImpl(){
  System.out.println("Starting up");
  try {
    ontology=new OntologyReader();
    clean=new TimerTask(){
      public void run(){
        long time=new GregorianCalendar().getTimeInMillis();
synchronized (userMap) {
          Iterator it=userMap.keySet().iterator();
          List<String> obsolete=new ArrayList<String>();
          while (it.hasNext()) {
            String key=(String)it.next();
            long timeDif=time - userMap.get(key).getLastUpdated();
            if ((timeDif < 0) || (timeDif > 3600000))             obsolete.add(key);
          }
          for (int i=0; i < obsolete.size(); i++)           userMap.remove(obsolete.get(i));
        }
      }
    }
;
    Timer timer=new Timer();
    timer.schedule(clean,0,600000);
    Runtime r=Runtime.getRuntime();
    r.gc();
    r.runFinalization();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 80

From project leviathan, under directory /common/src/main/java/ar/com/zauber/leviathan/common/async/.

Source file: JobScheduler.java

  30 
vote

@Override protected void doJob(final Job job){
  final Future<?> future=executorService.submit(job);
  if (timer != null && !future.isDone()) {
    timer.schedule(new TimerTask(){
      @Override public void run(){
        if (!future.isDone()) {
          future.cancel(true);
          if (logger.isDebugEnabled()) {
            logger.debug("Timeout while processing job " + job);
          }
        }
      }
    }
,timeout);
  }
}
 

Example 81

From project madvertise-android-sdk, under directory /madvertiseSDK/src/de/madvertise/android/sdk/.

Source file: MadvertiseView.java

  30 
vote

/** 
 * Handles the refresh timer, initiates the stopping of the request thread and caching of ads.
 * @param starting
 */
private void onViewCallback(final boolean starting){
synchronized (this) {
    if (starting) {
      if (mAdTimer == null) {
        mAdTimer=new Timer();
        mAdTimer.schedule(new TimerTask(){
          public void run(){
            MadvertiseUtil.logMessage(null,Log.DEBUG,"Refreshing ad ...");
            requestNewAd(true);
          }
        }
,(long)mSecondsToRefreshAd * 1000,(long)mSecondsToRefreshAd * 1000);
      }
    }
 else {
      if (mAdTimer != null) {
        MadvertiseUtil.logMessage(null,Log.DEBUG,"Stopping refresh timer ...");
        mAdTimer.cancel();
        mAdTimer=null;
        stopRequestThread();
      }
    }
  }
}
 

Example 82

From project moho, under directory /moho-sample/Outbound/src/main/java/com/voxeo/moho/sample/.

Source file: Outbound.java

  30 
vote

@Override public void init(final ApplicationContext ctx){
  _party1=(CallableEndpoint)ctx.createEndpoint(ctx.getParameter("party1"));
  _party2=(CallableEndpoint)ctx.createEndpoint(ctx.getParameter("party2"));
  _local=(CallableEndpoint)ctx.createEndpoint("sip:mohosample@example.com");
  final long time=Long.parseLong(ctx.getParameter("time"));
  _timer=new Timer();
  _timer.schedule(new TimerTask(){
    @Override public void run(){
      final Call c1=_party1.call(_local);
      final Call c2=_party2.call(_local);
      c1.join(c2,JoinType.DIRECT,Direction.DUPLEX);
    }
  }
,time);
}
 

Example 83

From project mythmote, under directory /src/tkj/android/homecontrol/mythmote/.

Source file: MythCom.java

  30 
vote

/** 
 * Creates the update timer and schedules it for the given interval. If the timer already exists it is destroyed and recreated. 
 */
private void scheduleUpdateTimer(int updateInterval){
  try {
    if (_timer != null) {
      _timer.cancel();
      _timer.purge();
      _timer=null;
    }
    if (timerTaskCheckStatus != null) {
      timerTaskCheckStatus.cancel();
      timerTaskCheckStatus=null;
    }
    if (updateInterval > 0) {
      timerTaskCheckStatus=new TimerTask(){
        public void run(){
          if (IsConnected() && !IsConnecting()) {
            if (queryMythScreen() == null) {
              setStatus("Disconnected",STATUS_DISCONNECTED);
            }
 else {
              setStatus(_frontend.Name + " - Connected",STATUS_CONNECTED);
            }
          }
        }
      }
;
      _timer=new Timer();
      _timer.schedule(timerTaskCheckStatus,updateInterval,updateInterval);
    }
  }
 catch (  Exception ex) {
    Log.e(MythMote.LOG_TAG,"Error scheduling status update timer.",ex);
  }
}
 

Example 84

From project ned-mobile-client, under directory /java/src/org/ned/client/view/.

Source file: VideoPlayerView.java

  30 
vote

public void startTimer(){
  cancelTimer();
  timer=new Timer();
  task=new TimerTask(){
    public void run(){
      try {
        updateProgressBar();
      }
 catch (      Exception ex) {
      }
    }
  }
;
  timer.schedule(task,SEC,SEC);
}
 

Example 85

From project omid, under directory /src/main/java/com/yahoo/omid/client/.

Source file: TSOClient.java

  30 
vote

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e) throws Exception {
  LOG.error("Unexpected exception",e.getCause());
synchronized (state) {
    if (state == State.CONNECTING) {
      state=State.RETRY_CONNECT_WAIT;
      if (LOG.isDebugEnabled()) {
        LOG.debug("Retrying connect in " + retry_delay_ms + "ms "+ retries);
      }
      try {
        retryTimer.schedule(new TimerTask(){
          public void run(){
synchronized (state) {
              state=State.DISCONNECTED;
              try {
                connectIfNeeded();
              }
 catch (              IOException e) {
                bailout(e);
              }
            }
          }
        }
,retry_delay_ms);
      }
 catch (      Exception cause) {
        bailout(cause);
      }
    }
 else {
      LOG.error("Exception on channel",e.getCause());
    }
  }
}
 

Example 86

From project onebusaway-android, under directory /src/com/joulespersecond/seattlebusbot/.

Source file: MySearchFragmentBase.java

  30 
vote

@Override public boolean onQueryTextChange(String newText){
  cancelDelayedSearch();
  if (newText.length() == 0) {
    return true;
  }
  final String query=newText;
  final Runnable doSearch=new Runnable(){
    public void run(){
      doSearch(query);
    }
  }
;
  mSearchTimer=new Timer();
  mSearchTimer.schedule(new TimerTask(){
    @Override public void run(){
      mSearchHandler.post(doSearch);
    }
  }
,DELAYED_SEARCH_TIMEOUT);
  return true;
}
 

Example 87

From project org.bonsaimind.bukkitplugins, under directory /SaveStopper/src/org/bonsaimind/bukkitplugins/savestopper/.

Source file: Plugin.java

  30 
vote

private void saveOffScheduled(){
  if (settings.getWait() > 0) {
    println("Disabling scheduled, " + settings.getWait() + " seconds.");
    currentTask=new TimerTask(){
      @Override public void run(){
        saveOff();
      }
    }
;
    timer.schedule(currentTask,settings.getWait() * 1000);
  }
 else {
    saveOff();
  }
}
 

Example 88

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/proxy/swing/.

Source file: ProxyPanel.java

  30 
vote

public void updateRow(final ConversationID id,String status){
  for (int i=0; i < _rows.size(); i++) {
    Object[] row=(Object[])_rows.get(i);
    if (row[1].equals(id)) {
      row[4]=status;
      fireTableCellUpdated(i,4);
      _timer.schedule(new TimerTask(){
        public void run(){
          removeRow(id);
        }
      }
,5000);
      return;
    }
  }
}
 

Example 89

From project PartyWare, under directory /android/src/com/google/zxing/client/android/wifi/.

Source file: Killer.java

  30 
vote

public void run(){
  final Handler handler=new Handler();
  Timer t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      handler.post(new Runnable(){
        public void run(){
          launchIntent(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com/")));
        }
      }
);
    }
  }
,DELAY_MS);
}
 

Example 90

From project platform_packages_apps_settings, under directory /src/com/android/settings/wifi/.

Source file: WpsDialog.java

  30 
vote

@Override protected void onStart(){
  mTimer=new Timer(false);
  mTimer.schedule(new TimerTask(){
    @Override public void run(){
      mHandler.post(new Runnable(){
        @Override public void run(){
          mTimeoutBar.incrementProgressBy(1);
        }
      }
);
    }
  }
,1000,1000);
  mContext.registerReceiver(mReceiver,mFilter);
  WpsInfo wpsConfig=new WpsInfo();
  wpsConfig.setup=mWpsSetup;
  mWifiManager.startWps(mChannel,wpsConfig,mWpsListener);
}
 

Example 91

From project Playlist, under directory /src/com/google/zxing/client/android/wifi/.

Source file: Killer.java

  30 
vote

public void run(){
  final Handler handler=new Handler();
  Timer t=new Timer();
  t.schedule(new TimerTask(){
    @Override public void run(){
      handler.post(new Runnable(){
        public void run(){
          launchIntent(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com/")));
        }
      }
);
    }
  }
,DELAY_MS);
}
 

Example 92

From project pluto, under directory /pluto-container-driver-api/src/main/java/org/apache/pluto/container/driver/.

Source file: PortletServlet.java

  30 
vote

/** 
 * Initialize the portlet invocation servlet.
 * @throws ServletException if an error occurs while loading portlet.
 */
public void init(ServletConfig config) throws ServletException {
  super.init(config);
  portletName=getInitParameter("portlet-name");
  started=false;
  startTimer=new Timer(true);
  final ServletContext servletContext=getServletContext();
  final ClassLoader paClassLoader=Thread.currentThread().getContextClassLoader();
  startTimer.schedule(new TimerTask(){
    public void run(){
synchronized (servletContext) {
        if (startTimer != null) {
          if (attemptRegistration(servletContext,paClassLoader)) {
            startTimer.cancel();
            startTimer=null;
          }
        }
      }
    }
  }
,1,10000);
}
 

Example 93

From project PocketMonstersOnline, under directory /Server/src/org/pokenet/server/backend/entity/.

Source file: HMObject.java

  30 
vote

@Override public void talkToPlayer(PlayerChar p){
  if (p.getTrainingLevel() >= getNecessaryTrainerLevel(getType())) {
switch (m_HMType) {
case STRENGTH_BOULDER:
      queueMovement(p.getFacing());
    if (addToMovementManager) {
      GameServer.getServiceManager().getMovementService().getMovementManager().addHMObject(this);
      addToMovementManager=false;
    }
  timer.schedule(new TimerTask(){
    public void run(){
      hmObj.setX(originalX);
      hmObj.setY(originalY);
    }
  }
,30000);
break;
case CUT_TREE:
case ROCKSMASH_ROCK:
case WHIRLPOOL:
getMap().removeChar(this);
timer.schedule(new TimerTask(){
public void run(){
m_map.addChar(hmObj);
}
}
,30000);
break;
}
}
 else {
p.getTcpSession().write("ch" + getNecessaryTrainerLevel(m_HMType));
}
}
 

Example 94

From project Racenet-for-Android, under directory /src/org/racenet/services/.

Source file: MQTTService.java

  30 
vote

private boolean connect(){
  String userId=db.get("user_id");
  if (userId.equals("")) {
    return false;
  }
  int interval=Integer.parseInt(db.get("ping"));
  client=new NettyClient("user_" + userId);
  client.setKeepAlive(0);
  client.setListener(new MQTTListener(this));
  client.connect("78.46.92.230",1883);
  pinger.schedule(new TimerTask(){
    @Override public void run(){
      if (!waitingForPong) {
        client.ping();
        waitingForPong=true;
        Log.d("MQTT","Ping sent");
      }
 else {
        Log.d("MQTT","Connection lost, trying to reconnect");
        waitingForPong=false;
        cancel();
        connect();
      }
    }
  }
,interval,interval);
  return true;
}
 

Example 95

From project reef-example-apps, under directory /apps/state-optimizer/src/main/java/org/totalgrid/reef/examples/stateoptimizer/.

Source file: StateOptimizerManager.java

  30 
vote

/** 
 * runs the optimize routine every periodMs
 */
public void run(){
  Timer timer=new Timer();
  timer.schedule(new TimerTask(){
    @Override public void run(){
      try {
        algorithm.optimize(new MeasurementState(measurementSubscriber.getCurrentState()),commandIssuer);
      }
 catch (      Exception e) {
        System.out.println("Error running optimize: " + e.getMessage());
        e.printStackTrace();
      }
    }
  }
,0,periodMs);
  try {
    System.out.println("Press Enter to quit...");
    System.in.read();
  }
 catch (  IOException e) {
  }
  timer.cancel();
}
 

Example 96

From project rj-servi, under directory /de.walware.rj.servi/src/de/walware/rj/servi/internal/.

Source file: NodeServer.java

  30 
vote

void shutdown(){
  this.control.checkCleanup();
  new Timer(true).schedule(new TimerTask(){
    @Override public void run(){
      try {
        unbindClient();
      }
 catch (      final Exception e) {
        e.printStackTrace();
      }
      System.exit(0);
    }
  }
,500L);
}
 

Example 97

From project Sage-Mobile-Calc, under directory /src/org/connectbot/service/.

Source file: TerminalManager.java

  30 
vote

public void addKey(PubkeyBean pubkey,Object trileadKey,boolean force){
  if (!savingKeys && !force)   return;
  removeKey(pubkey.getNickname());
  byte[] sshPubKey=PubkeyUtils.extractOpenSSHPublic(trileadKey);
  KeyHolder keyHolder=new KeyHolder();
  keyHolder.bean=pubkey;
  keyHolder.trileadKey=trileadKey;
  keyHolder.openSSHPubkey=sshPubKey;
  loadedKeypairs.put(pubkey.getNickname(),keyHolder);
  if (pubkey.getLifetime() > 0) {
    final String nickname=pubkey.getNickname();
    pubkeyTimer.schedule(new TimerTask(){
      @Override public void run(){
        Log.d(TAG,"Unloading from memory key: " + nickname);
        removeKey(nickname);
      }
    }
,pubkey.getLifetime() * 1000);
  }
  Log.d(TAG,String.format("Added key '%s' to in-memory cache",pubkey.getNickname()));
}
 

Example 98

From project sandbox_2, under directory /wicket-cluster/wicket-cluster-jetty/src/main/java/org/apache/wicket/cluster/jetty/.

Source file: HashSessionManager.java

  30 
vote

public void setScavengePeriod(int seconds){
  if (seconds == 0)   seconds=60;
  int old_period=scavengePeriodMs;
  int period=seconds * 1000;
  if (period > 60000)   period=60000;
  if (period < 1000)   period=1000;
  scavengePeriodMs=period;
  if (timer != null && (period != old_period || task == null)) {
synchronized (this) {
      if (task != null)       task.cancel();
      task=new TimerTask(){
        public void run(){
          scavenge();
        }
      }
;
      timer.schedule(task,scavengePeriodMs,scavengePeriodMs);
    }
  }
}
 

Example 99

From project scisoft-ui, under directory /uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/views/.

Source file: AsciiTextView.java

  30 
vote

private void updateMonitoring(){
  final IToolBarManager toolbarManager=getViewSite().getActionBars().getToolBarManager();
  final IContributionItem[] items=toolbarManager.getItems();
  for (int i=0; i < items.length; i++) {
    if (items[i] instanceof CommandContributionItem) {
      final CommandContributionItem c=(CommandContributionItem)items[i];
      if (c.getId().equals(AsciiMonitorAction.ID)) {
        try {
          final Method method=CommandContributionItem.class.getDeclaredMethod("setChecked",boolean.class);
          method.setAccessible(true);
          method.invoke(c,monitoringFile);
        }
 catch (        Exception ignored) {
        }
      }
    }
  }
  if (monitoringFile) {
    this.timer=new Timer("Update text timer",false);
    this.timer.schedule(new TimerTask(){
      @Override public void run(){
        getSite().getShell().getDisplay().asyncExec(new Runnable(){
          @Override public void run(){
            final String allText=refreshFile();
            text.setSelection(allText.lastIndexOf('\n') + 1);
          }
        }
);
      }
    }
,0,5000);
  }
 else {
    if (timer != null)     this.timer.cancel();
  }
}
 

Example 100

From project smart-cms, under directory /spi-modules/content-spi-dist-lock-impl/src/main/java/com/smartitengineering/cms/spi/lock/impl/distributed/.

Source file: LocalLockRegistrarImpl.java

  30 
vote

@Inject public void initTimeoutChecking(){
  timer.schedule(new TimerTask(){
    @Override public void run(){
      lock.lock();
      List<Entry<Key,LockDetails>> removables=new ArrayList<Entry<Key,LockDetails>>();
      try {
        long currentTime=System.currentTimeMillis();
        final Set<Entry<Key,LockDetails>> entrySet=lockMap.entrySet();
        for (        Entry<Key,LockDetails> entry : entrySet) {
          if (currentTime >= entry.getValue().getTimeoutTime()) {
            removables.add(new SimpleEntry<Key,LockDetails>(entry.getKey(),lockMap.get(entry.getKey())));
          }
        }
      }
 catch (      Exception ex) {
        logger.warn(ex.getMessage(),ex);
      }
 finally {
        lock.unlock();
      }
      for (      Entry<Key,LockDetails> removable : removables) {
        unlock(removable.getKey(),removable.getValue().getLockId());
        removable.getValue().getListener().lockTimedOut(removable.getKey());
      }
    }
  }
,localLockTimeout,localLockTimeout);
}
 

Example 101

From project SOAj, under directory /soaj-core/src/main/java/info/soaj/core/rf/.

Source file: SjcTimerRF.java

  30 
vote

/** 
 * Schedule a Controller to be processed a certain number of milliseconds in the future.
 */
@Override public void schedule(final long millisInFuture,final SjcProcessMethodSI processMethodSI){
  final String Method_Name="schedule";
  final Timer timer=new Timer();
  if (retrievePluginPropertyPO().getPropertyBoolean(SjcTimerRF.DECLARATIVE_LOGGING_TASK_SCHEDULED)) {
    SjcLogUtil.logDeclarative(SjcTimerRF.CLASS_NAME,Method_Name," *Scheduled Task* = " + processMethodSI.getClass().getSimpleName() + "#"+ processMethodSI.hashCode()+ "; "+ new Date(System.currentTimeMillis() + millisInFuture));
  }
  this.threadLocalCO=SjcThreadLocalUtil.getThreadLocalCO();
  timer.schedule(new TimerTask(){
    @SuppressWarnings("synthetic-access") @Override public void run(){
      SjcThreadLocalUtil.setThreadLocalCO(SjcTimerRF.this.threadLocalCO);
      if (retrievePluginPropertyPO().getPropertyBoolean(SjcTimerRF.DECLARATIVE_LOGGING_TASK_LAUNCHED)) {
        SjcLogUtil.logDeclarative(SjcTimerRF.CLASS_NAME,Method_Name," *Launched Task* = " + processMethodSI.getClass().getSimpleName() + "#"+ processMethodSI.hashCode()+ "; "+ new Date(System.currentTimeMillis() + millisInFuture));
      }
      processMethodSI.process();
      if (retrievePluginPropertyPO().getPropertyBoolean(SjcTimerRF.DECLARATIVE_LOGGING_TASK_COMPLETED)) {
        SjcLogUtil.logDeclarative(SjcTimerRF.CLASS_NAME,Method_Name," *Completed Task* = " + processMethodSI.getClass().getSimpleName() + "#"+ processMethodSI.hashCode()+ "; "+ new Date(System.currentTimeMillis() + millisInFuture));
      }
      timer.cancel();
    }
  }
,millisInFuture);
}
 

Example 102

From project SOCIETIES-SCE-Services, under directory /3rdPartyServices/DisasterManagement/IJacket/ijacket/src/main/java/org/societies/thirdpartyservices/ijacket/.

Source file: JacketMenuActivity.java

  30 
vote

public void onClick(View v){
  timer.schedule(new TimerTask(){
    public void run(){
      try {
        Vibrator vib=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(2000);
        IJacketApp appState=((IJacketApp)getApplicationContext());
        BluetoothConnection con=appState.getCon();
        con.write(pin,true,false);
        Thread.sleep(2000);
        con.write(pin,false,false);
      }
 catch (      Exception e) {
        quickToastMessage(e.getMessage());
      }
    }
  }
,0);
}
 

Example 103

From project socorro-hazelcast-poc, under directory /src/com/hazelcast/socorro/.

Source file: Collector.java

  30 
vote

private void generateCrashReportsPeriodically(){
  final Random random=new Random();
  Timer timer=new Timer();
  timer.schedule(new TimerTask(){
    @Override public void run(){
      int k=LOAD / (Hazelcast.getCluster().getMembers().size() * 60);
      for (int i=0; i < k; i++) {
        CrashReport crashReport=new CrashReport(CrashReport.generateMap(),new byte[randomSizeForBlob() * KILO_BYTE]);
        crashReport.setId(Hazelcast.getIdGenerator("ids").newId());
        generatedCrashReports.offer(crashReport);
      }
      logger.info("Generated " + k + " number of Crash Reports. Current size in the local Q is: "+ generatedCrashReports.size());
    }
  }
,0,1000);
}
 

Example 104

From project soja, under directory /soja-core/src/main/java/com/excilys/soja/core/handler/.

Source file: StompHandler.java

  30 
vote

/** 
 * Start a scheduler for the heart-beating system.
 * @param channel
 * @param remoteExpectedHeartBeat
 */
public boolean startLocalHeartBeat(final Channel channel,final Frame frame){
  String heartBeatString=frame.getHeaderValue(Header.HEADER_HEART_BEAT);
  if (heartBeatString != null) {
    String[] heartBeat=heartBeatString.split(",");
    if (heartBeat.length == 2) {
      long remoteExpectedHeartBeat=Long.parseLong(heartBeat[1]);
      if (localGuaranteedHeartBeat != 0 && remoteExpectedHeartBeat != 0) {
        long heartBeatInterval=Math.max(localGuaranteedHeartBeat,remoteExpectedHeartBeat);
        localHeartBeartTimer=new Timer("Heart-beating");
        localHeartBeartTimer.scheduleAtFixedRate(new TimerTask(){
          @Override public void run(){
            try {
              sendFrame(channel,new HeartBeatFrame());
            }
 catch (            SocketException e) {
              e.printStackTrace();
            }
          }
        }
,0,heartBeatInterval);
        return true;
      }
    }
  }
  return false;
}
 

Example 105

From project Sourcerer, under directory /infrastructure/utils/utilities/src/edu/uci/ics/sourcerer/util/.

Source file: TimeoutManager.java

  30 
vote

public synchronized T get(){
  lastTimeAccessed=System.currentTimeMillis();
  if (instance == null) {
    instance=instantiator.create();
    if (instance != null) {
      Timer timer=new Timer();
      task=new TimerTask(){
        @Override public void run(){
synchronized (TimeoutManager.this) {
            if (System.currentTimeMillis() - lastTimeAccessed > TIMEOUT) {
              logger.info("Timeout manager closing...");
              IOUtils.close(instance);
              instance=null;
              task=null;
              this.cancel();
            }
          }
        }
      }
;
      timer.schedule(task,TIMEOUT,TIMEOUT);
    }
  }
  return instance;
}
 

Example 106

From project SVQCOM, under directory /Core/src/com/ushahidi/android/app/.

Source file: BackgroundService.java

  30 
vote

/** 
 * Starts the background service
 * @return void
 */
private void startService(){
  Preferences.loadSettings(mContext);
  long period=(1 * 60000);
  long delay=500;
  mDoTask=new TimerTask(){
    @Override public void run(){
      handler.post(new Runnable(){
        public void run(){
          ApiUtils.fetchReports(BackgroundService.this);
          showNotification(Preferences.totalReportsFetched);
        }
      }
);
    }
  }
;
  mT.scheduleAtFixedRate(mDoTask,delay,period);
}
 

Example 107

From project syncany, under directory /syncany/src/name/pachler/nio/file/contrib/.

Source file: BufferedWatcher.java

  30 
vote

public synchronized void start(){
  if (worker != null) {
    return;
  }
  worker=new Thread(new WatchWorker(),"BufWatchWorker");
  worker.start();
  timer=new Timer("BufWatchTimer");
  timer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      try {
        fireDelayedEvents();
      }
 catch (      Exception e) {
        logger.log(Level.WARNING,"Error while processing delayed events. IGNORING.",e);
      }
    }
  }
,0,delay);
}
 

Example 108

From project TeamMeet, under directory /android/src/de/teammeet/service/.

Source file: TeamMeetLocationListener.java

  30 
vote

public TeamMeetLocationListener(final ServiceInterfaceImpl serviceInterface,final Handler messageHandler,final Resources res){
  mServiceInterface=serviceInterface;
  mMessageHandler=messageHandler;
  mResources=res;
  mTimeout=mResources.getInteger(R.integer.server_timeout);
  mTimer=new Timer(CLASS,true);
  mTimerTask=new TimerTask(){
    @Override public void run(){
      if (mLocation != null && mLocation != mLastLocation) {
        serviceInterface.sendLocation(mLocation,mAccuracy);
        showToast("Location update to: " + mLocation.toString());
        Log.d(CLASS,"Location update to: " + mLocation.toString());
        mLastLocation=mLocation;
      }
    }
  }
;
  mTimer.scheduleAtFixedRate(mTimerTask,mTimeout,mTimeout);
}
 

Example 109

From project ToolkitForAndroid, under directory /src/main/java/com/apkits/android/system/.

Source file: DClickExit.java

  30 
vote

/** 
 * ?????????????????????
 * @param keyCode ???ID
 * @param tip ??????
 * @param waitTime ????????
 * @return false
 */
public boolean dClickExit(int keyCode,String tip,int waitTime){
  if (keyCode == KeyEvent.KEYCODE_BACK) {
    if (mIsExit == false) {
      mIsExit=true;
      Toast.makeText(mContext,tip,Toast.LENGTH_SHORT).show();
      if (!mHasTask) {
        new Timer().schedule(new TimerTask(){
          @Override public void run(){
            mIsExit=false;
            mHasTask=true;
          }
        }
,waitTime);
      }
    }
 else {
      mContext.finish();
      android.os.Process.killProcess(android.os.Process.myPid());
    }
  }
  return false;
}
 

Example 110

From project TransportsRennes, under directory /TransportsBordeaux/src/fr/ybo/transportsbordeaux/map/mapviewutil/markerclusterer/.

Source file: GeoClusterer.java

  30 
vote

/** 
 * Hooking draw event from ClusterMarker to detect zoom/move event. hope there will be event notification for android equivalent to javascriptin the future....
 */
private void onNotifyDrawFromCluster(){
  if (isMoving) {
    return;
  }
  GeoBounds curBnd=getCurBounds();
  if (!savedBounds.isEqual(curBnd)) {
    isMoving=true;
    savedBounds=curBnd;
    Timer timer=new Timer(true);
    timer.schedule(new TimerTask(){
      @Override public void run(){
        GeoBounds curBnd=getCurBounds();
        if (savedBounds.isEqual(curBnd)) {
          isMoving=false;
          cancel();
          handler.post(new Runnable(){
            public void run(){
              resetViewport();
            }
          }
);
        }
        savedBounds=curBnd;
      }
    }
,500,500);
  }
}
 

Example 111

From project vcloud, under directory /async-cache/src/main/java/com/jbrisbin/vcloud/cache/.

Source file: RabbitMQAsyncCache.java

  30 
vote

@Override public void start(){
  active.set(true);
  try {
    Channel channel=getConnection().createChannel();
    channel.exchangeDeclare(objectRequestExchange,"topic",true,false,null);
    channel.queueDeclare(id,true,false,true,null);
  }
 catch (  IOException e) {
    log.error(e.getMessage(),e);
  }
  for (int i=0; i < maxWorkers; i++) {
    activeTasks.add(workerPool.submit(new ObjectSender()));
    activeTasks.add(workerPool.submit(new CommandSender()));
    workerPool.submit(new Runnable(){
      @Override public void run(){
        try {
          Channel channel=getConnection().createChannel();
          ObjectLoadMonitor loadMonitor=new ObjectLoadMonitor(channel);
          channel.basicConsume(id,loadMonitor);
        }
 catch (        IOException e) {
          log.error(e.getMessage(),e);
        }
      }
    }
);
  }
  activeTasks.add(workerPool.submit(new HeartbeatMonitor()));
  commandMessages.add(new CommandMessage("ping",heartbeatExchange,""));
  delayTimer.scheduleAtFixedRate(new TimerTask(){
    @Override public void run(){
      if (cacheNodes.size() > 0) {
        numOfCacheNodes.set(cacheNodes.size());
      }
    }
  }
,0,heartbeatInterval);
}
 

Example 112

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/poolable/copy/.

Source file: EvictionTimer.java

  29 
vote

/** 
 * Add the specified eviction task to the timer. Tasks that are added with a call to this method *must* call  {@link #cancel(TimerTask)} to cancel thetask to prevent memory and/or thread leaks in application server environments.
 * @param task      Task to be scheduled
 * @param delay     Delay in milliseconds before task is executed
 * @param period    Time in milliseconds between executions
 */
static synchronized void schedule(TimerTask task,long delay,long period){
  if (null == _timer) {
    _timer=new Timer(true);
  }
  _usageCount++;
  _timer.schedule(task,delay,period);
}
 

Example 113

From project freemind, under directory /freemind/freemind/modes/common/plugins/.

Source file: ReminderHookBase.java

  29 
vote

private void scheduleTimer(MindMapNode node,TimerTask task){
  timer=new Timer();
  Date date=new Date(remindUserAt);
  timer.schedule(task,date);
  Object[] messageArguments={date};
  MessageFormat formatter=new MessageFormat(getResourceString("plugins/TimeManagement.xml_reminderNode_tooltip"));
  String message=formatter.format(messageArguments);
  setToolTip(node,getName(),message);
  displayState(CLOCK_VISIBLE,getNode(),false);
}
 

Example 114

From project gerrit-trigger-plugin, under directory /gerrithudsontrigger/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/hudsontrigger/.

Source file: GerritTriggerTimer.java

  29 
vote

/** 
 * Schedule a TimerTask according to the two constants above.
 * @param timerTask the subclass of TimerTask to be scheduled
 */
public void schedule(TimerTask timerTask){
  long timerPeriod=MILLISECONDS_PER_SECOND * PluginImpl.getInstance().getConfig().getDynamicConfigRefreshInterval();
  try {
    timer.schedule(timerTask,DELAY_MILLISECONDS,timerPeriod);
  }
 catch (  IllegalArgumentException iae) {
    logger.error("Attempted use of negative delay",iae);
  }
catch (  IllegalStateException ise) {
    logger.error("Attempted re-use of TimerTask",ise);
  }
}
 

Example 115

From project moji, under directory /src/test/java/fm/last/moji/tracker/pool/.

Source file: ManagedTrackerHostTest.java

  29 
vote

@Before public void setup(){
  managedTrackerHost=new ManagedTrackerHost(mockAddress,mockTimer,mockClock);
  managedTrackerHost.setHostRetryInterval(10,MILLISECONDS);
  managedTrackerHost.resetTaskFactory=mockTaskFactory;
  actualTask=managedTrackerHost.new ResetTask();
  doNothing().when(mockTimer).schedule(any(TimerTask.class),eq(1L));
  when(mockClock.currentTimeMillis()).thenReturn(1L,2L,3L);
  when(mockTaskFactory.newInstance()).thenReturn(mockTask,actualTask);
}
 

Example 116

From project riftsaw-ode, under directory /bpel-epr/src/main/java/org/apache/ode/il/.

Source file: MockScheduler.java

  29 
vote

public String scheduleVolatileJob(final boolean transacted,final JobDetails detail,final Date date) throws ContextException {
  if (date != null) {
    registerSynchronizer(new Synchronizer(){
      public void afterCompletion(      boolean success){
        if (!success)         return;
        _timer.schedule(new TimerTask(){
          @SuppressWarnings("unchecked") public void run(){
            exec(transacted,detail);
          }
        }
,date);
      }
      public void beforeCompletion(){
      }
    }
);
    return null;
  }
 else {
    registerSynchronizer(new Synchronizer(){
      @SuppressWarnings("unchecked") public void afterCompletion(      boolean success){
        if (!success)         return;
        exec(transacted,detail);
      }
      public void beforeCompletion(){
      }
    }
);
    return null;
  }
}
 

Example 117

From project scooter, under directory /source/src/com/scooterframework/admin/.

Source file: DirChangeMonitor.java

  29 
vote

private void schedule(TimerTask task,long period){
  if (period > 0) {
    timer.schedule(task,oldDate,period);
  }
 else {
    timer.schedule(task,oldDate);
  }
}
 

Example 118

From project spring-js, under directory /src/main/java/org/springframework/scheduling/timer/.

Source file: ScheduledTimerTask.java

  29 
vote

/** 
 * Create a new ScheduledTimerTask.
 * @param timerTask the TimerTask to schedule
 * @param delay the delay before starting the task for the first time (ms)
 * @param period the period between repeated task executions (ms)
 * @param fixedRate whether to schedule as fixed-rate execution
 */
public ScheduledTimerTask(TimerTask timerTask,long delay,long period,boolean fixedRate){
  this.timerTask=timerTask;
  this.delay=delay;
  this.period=period;
  this.fixedRate=fixedRate;
}