Java Code Examples for java.util.Timer
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 bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.
Source file: BioportalRestService.java

/** * 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 2
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.
Source file: SearchCatalogue.java

/** * Stop the timer. */ private void stopIdleTimer(){ Timer tmr; synchronized (SearchCatalogue.this) { tmr=mTimer; mTimer=null; } if (tmr != null) tmr.cancel(); }
Example 3
From project jPOS, under directory /jpos/src/main/java/org/jpos/util/.
Source file: RotateLogListener.java

/** * @param name base log filename * @param sleepTime switch logs every t seconds * @param maxCopies number of old logs * @param maxSize in bytes */ public RotateLogListener(String logName,int sleepTime,int maxCopies,long maxSize) throws IOException { super(); this.logName=logName; this.maxCopies=maxCopies; this.sleepTime=sleepTime * 1000; this.maxSize=maxSize; f=null; openLogFile(); Timer timer=DefaultTimer.getTimer(); if (sleepTime != 0) { timer.schedule(rotate=new Rotate(),this.sleepTime,this.sleepTime); } }
Example 4
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.
Source file: ErrorDisplayer.java

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 5
From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/fedora/.
Source file: AccessControlUtils.java

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 6
From project en, under directory /src/l1j/server/server/model/Instance/.
Source file: L1ItemInstance.java

public void startEquipmentTimer(L1PcInstance pc){ if (getRemainingTime() > 0) { _equipmentTimer=new L1EquipmentTimer(pc,this); Timer timer=new Timer(true); timer.scheduleAtFixedRate(_equipmentTimer,1000,1000); } }
Example 7
From project facebook-android-sdk, under directory /examples/Hackbook/src/com/facebook/android/.
Source file: SplashActivity.java

@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 8
From project floodlight, under directory /src/main/java/net/floodlightcontroller/core/.
Source file: OFMessageFilterManager.java

public void run(){ int x=filterManager.timeoutFilters(); if (x > 0) { Timer timer=new Timer(); timer.schedule(new TimeoutFilterTask(filterManager),TIMER_INTERVAL); } else { } }
Example 9
From project harmony, under directory /harmony.adapter.uclp/src/main/java/org/opennaas/extensions/idb/da/argia/webservice/.
Source file: StartupServlet.java

/** * 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 10
From project jtrek, under directory /src/org/gamehost/jtrek/javatrek/.
Source file: TrekObserverDevice.java

protected void kill(){ tower=null; destroyed=true; currentQuadrant.removeObjectByScanLetter(scanLetter); Timer recreateTimer=new Timer("Observer-" + name); recreateTimer.schedule(new TrekRegenerateObs(this),regenTime); }
Example 11
From project kevoree-library, under directory /kalimucho/org.kevoree.library.kalimucho.kalimuchoNode/src/main/java/platform/plugins/installables/application/.
Source file: BCCommandSenderPlugin.java

/** * Used by the BCs to get the replies from platforms * @param demandeur the BC which waits for reply * @param attente time out (in ms) for waiting for reply * @return the platform's replie * @throws InterruptedException if the BC is stopped by the platform */ public PlatformReplyMessage getPlatformReply(BCModel demandeur,int attente) throws InterruptedException { synchronized (demandeur) { String own=demandeur.getName(); NetworkPlatformMessage recu=null; Timer delai=new Timer(); timeOut=false; delai.schedule(new TimeOut(own),attente); recu=boiteDeReponses.retirerMessageInterruptible(own); delai.cancel(); if (recu != null) return new PlatformReplyMessage(recu); else return null; } }
Example 12
From project mixare, under directory /src/org/mixare/mgr/location/.
Source file: LocationMgrImpl.java

private void requestBestLocationUpdates(){ Timer timer=new Timer(); for ( String p : lm.getAllProviders()) { if (lm.isProviderEnabled(p)) { LocationResolver lr=new LocationResolver(lm,p,this); locationResolvers.add(lr); lm.requestLocationUpdates(p,0,0,lr); } } timer.schedule(new LocationTimerTask(),20 * 1000); }
Example 13
From project mobilis, under directory /DemoServices/TreasureHunt/src/de/treasurehunt/.
Source file: TreasureHunt.java

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 14
From project ned-mobile-client, under directory /java/src/org/ned/client/view/.
Source file: VideoPlayerView.java

private void NotSupportedMediaContolAction(){ progress.setRenderPercentageOnTop(false); progress.setText(NedResources.NOT_SUPPORTED); Timer timer=new Timer(); timer.schedule(new FadingNotSupportedLabelTask(timer),1000); }
Example 15
public void popupSetBuildRequest(int coord,int ptype){ if (coord == -1) coord=0; Timer piTimer=playerInterface.getEventTimer(); synchronized (piTimer) { if (buildReqTimerTask != null) { buildReqTimerTask.doNotSend(); buildReqTimerTask.cancel(); } buildReqTimerTask=new BoardPanelSendBuildTask(coord,ptype); piTimer.schedule(buildReqTimerTask,1000 * BUILD_REQUEST_MAX_DELAY_SEC); } }
Example 16
From project PocketVDC, under directory /src/sate/pocketvdc/activities/.
Source file: SplashActivity.java

@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 17
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/poolable/copy/.
Source file: EvictionTimer.java

/** * 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 18
From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/camera/.
Source file: AutoFocusManager.java

AutoFocusManager(Context context,Camera camera){ this.camera=camera; timer=new Timer(true); SharedPreferences sharedPrefs=PreferenceManager.getDefaultSharedPreferences(context); String currentFocusMode=camera.getParameters().getFocusMode(); useAutoFocus=sharedPrefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS,true) && FOCUS_MODES_CALLING_AF.contains(currentFocusMode); Log.i(TAG,"Current focus mode '" + currentFocusMode + "'; use auto focus? "+ useAutoFocus); manual=false; checkAndStart(); }
Example 19
From project androidquery, under directory /beta/com/androidquery/callback/.
Source file: LocationAjaxCallback.java

private void work(){ Location loc=getBestLocation(); Timer timer=new Timer(false); if (networkEnabled) { AQUtility.debug("register net"); networkListener=new Listener(); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,interval,0,networkListener,Looper.getMainLooper()); timer.schedule(networkListener,timeout); } if (gpsEnabled) { AQUtility.debug("register gps"); gpsListener=new Listener(); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,interval,0,gpsListener,Looper.getMainLooper()); timer.schedule(gpsListener,timeout); } if (iteration > 1 && loc != null) { n++; callback(loc); } initTime=System.currentTimeMillis(); }
Example 20
From project androidtracks, under directory /src/org/sfcta/cycletracks/.
Source file: RecordingActivity.java

@Override public void onResume(){ super.onResume(); timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask(){ @Override public void run(){ mHandler.post(mUpdateTimer); } } ,0,1000); }
Example 21
From project android_packages_apps_QiblaCompass, under directory /src/com/farsitel/qiblacompass/activities/.
Source file: QiblaActivity.java

private void schedule(){ if (timer == null) { timer=new Timer(); this.timer.schedule(getTimerTask(),0,200); } else { timer.cancel(); timer=new Timer(); timer.schedule(getTimerTask(),0,200); } }
Example 22
From project asterisk-java, under directory /src/main/java/org/asteriskjava/live/internal/.
Source file: AsteriskQueueImpl.java

AsteriskQueueImpl(AsteriskServerImpl server,String name,Integer max,String strategy,Integer serviceLevel,Integer weight){ super(server); this.name=name; this.max=max; this.strategy=strategy; this.serviceLevel=serviceLevel; this.weight=weight; entries=new ArrayList<AsteriskQueueEntryImpl>(25); listeners=new ArrayList<AsteriskQueueListener>(); members=new HashMap<String,AsteriskQueueMemberImpl>(); timer=new Timer("ServiceLevelTimer-" + name,true); serviceLevelTimerTasks=new HashMap<AsteriskQueueEntry,ServiceLevelTimerTask>(); }
Example 23
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/cron/.
Source file: CronService.java

/** * Constructs cron jobs and schedules them. */ public static void start(){ LOGGER.info("Constructing Cron Service...."); CRONS.clear(); final RuntimeEnv runtimeEnv=Latkes.getRuntimeEnv(); try { switch (runtimeEnv) { case LOCAL: loadCronXML(); for ( final Cron cron : CRONS) { cron.setURL(Latkes.getServer() + Latkes.getContextPath() + cron.getUrl()); final Timer timer=new Timer(); timer.scheduleAtFixedRate(cron,Cron.SIXTY * Cron.THOUSAND,cron.getPeriod()); LOGGER.log(Level.FINER,"Scheduled a cron job[url={0}]",cron.getUrl()); } LOGGER.log(Level.FINER,"[{0}] cron jobs",CRONS.size()); break; case GAE: break; case BAE: break; default : throw new RuntimeException("Latke runs in the hell.... Please set the enviornment correctly"); } } catch (final Exception e) { throw new RuntimeException("Can not initialize Cron Service!",e); } LOGGER.info("Constructed Cron Service"); }
Example 24
public Input(BFrame frame){ frame.canvas.addMouseMotionListener(this); frame.canvas.addMouseListener(this); frame.canvas.addMouseWheelListener(this); frame.canvas.addKeyListener(this); size=new Dimension(); size.width=((JPanel)frame.getContentPane()).getWidth(); size.height=((JPanel)frame.getContentPane()).getHeight(); pressedKeys=new HashMap<Integer,Remover>(); keyBuffer=new ArrayList<Character>(); timer=new Timer(); }
Example 25
From project BetterShop_1, under directory /src/me/jascotty2/bettershop/spout/gui/.
Source file: MarketItemDetail.java

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 26
From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/activity/social/.
Source file: ChatActivity.java

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 27
From project BioMAV, under directory /ParrotControl/JavaDroneControl/src/nl/ru/ai/projects/parrot/dronecontrol/javadronecontrol/test/.
Source file: Test01.java

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 28
From project ceres, under directory /ceres-jai/src/test/java/com/bc/ceres/jai/operator/.
Source file: GameOfLifeTestMain.java

public void run(){ image=new BufferedImage(512,512,BufferedImage.TYPE_BYTE_GRAY); final byte[] bytes=((DataBufferByte)image.getRaster().getDataBuffer()).getData(); for (int i=0; i < bytes.length; i++) { bytes[i]=(byte)(Math.random() < 0.5 ? 0 : 255); } SwingUtilities.invokeLater(new Runnable(){ public void run(){ label=new JLabel(new ImageIcon(image)); frame=new JFrame("GoL"); frame.getContentPane().add(label); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter(){ @Override public void windowOpened( WindowEvent e){ final Timer timer=new Timer(); timer.schedule(new MyTimerTask(),1000,IMAGE_UPDATE_PERIOD); } } ); frame.setVisible(true); } } ); }
Example 29
From project chililog-server, under directory /src/main/java/org/chililog/server/.
Source file: App.java

/** * 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 30
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/adaptor/sigar/.
Source file: SystemMetrics.java

@Override public void start(long offset) throws AdaptorException { if (timer == null) { timer=new Timer(); runner=new SigarRunner(dest,SystemMetrics.this); } timer.scheduleAtFixedRate(runner,0,period); }
Example 31
From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/session/.
Source file: SessionManager.java

@Override protected void doStart() throws Exception { super.doStart(); if (_timer == null) { _timer=new Timer("session-scavenger",true); } setScavengePeriod(getScavengePeriod()); }
Example 32
From project CIShell, under directory /core/org.cishell.reference/src/org/cishell/reference/app/service/scheduler/.
Source file: SchedulerServiceImpl.java

private final void initialize(){ this.schedulerTimer=new Timer(true); this.schedulerListenerInformer=new SchedulerListenerInformer(); this.algorithmSchedulerTask=new AlgorithmSchedulerTask(this.schedulerListenerInformer); this.schedulerTimer.schedule(this.algorithmSchedulerTask,0L,500L); }
Example 33
From project codjo-data-process, under directory /codjo-data-process-gui/src/main/java/net/codjo/dataprocess/gui/plugin/.
Source file: DataProcessGuiPlugin.java

private void startServerPingTask(){ if (configuration.getServerPingDelay() != 0) { new Timer().schedule(new ServerPingTask(),0,configuration.getServerPingDelay()); } else { try { UserLoginTrackerClientHelper.addUser(ctxt,buildUserLoginTracker()); } catch ( Exception ex) { Log.error(getClass(),"Erreur interne concernant le suivie des personnes connect?s.",ex); } } }
Example 34
From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.
Source file: ConnectionManager.java

/** * 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 35
From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.
Source file: EvictionTimer.java

/** * 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) { ClassLoader ccl=(ClassLoader)AccessController.doPrivileged(new PrivilegedGetTccl()); try { AccessController.doPrivileged(new PrivilegedSetTccl(EvictionTimer.class.getClassLoader())); _timer=new Timer(true); } finally { AccessController.doPrivileged(new PrivilegedSetTccl(ccl)); } } _usageCount++; _timer.schedule(task,delay,period); }
Example 36
From project connectbot, under directory /src/sk/vx/connectbot/service/.
Source file: TerminalManager.java

private void stopWithDelay(){ if (loadedKeypairs.size() > 0) { synchronized (this) { if (idleTimer == null) idleTimer=new Timer("idleTimer",true); idleTimer.schedule(new IdleTask(),IDLE_TIMEOUT); } } else { Log.d(TAG,"Stopping service immediately"); stopSelf(); } }
Example 37
From project daap, under directory /src/main/java/org/ardverk/daap/.
Source file: AutoCommitTransaction.java

private synchronized void createTransactionIfNecessary(){ touch(); if (transaction == null) { transaction=library.beginTransaction(); if (timer == null) { timer=new Timer(); } if (commitTask == null) { commitTask=new CommitTask(); timer.scheduleAtFixedRate(commitTask,1000,500); } } }
Example 38
From project data-bus, under directory /databus-worker/src/test/java/com/inmobi/databus/.
Source file: DatabusTest.java

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 39
From project dmix, under directory /JmDNS/src/javax/jmdns/impl/.
Source file: DNSTaskStarter.java

public DNSTaskStarterImpl(JmDNSImpl jmDNSImpl){ super(); _jmDNSImpl=jmDNSImpl; _timer=new Timer("JmDNS(" + _jmDNSImpl.getName() + ").Timer",true); _stateTimer=new Timer("JmDNS(" + _jmDNSImpl.getName() + ").State.Timer",false); }
Example 40
From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/stats/.
Source file: Stats.java

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 41
From project ElectricSleep, under directory /src/com/androsz/electricsleepbeta/app/.
Source file: SleepMonitoringService.java

@Override public void onCreate(){ super.onCreate(); mRunning=new AtomicBoolean(); final IntentFilter filter=new IntentFilter(Alarms.ALARM_DISMISSED_BY_USER_ACTION); filter.addAction(Alarms.ALARM_SNOOZE_CANCELED_BY_USER_ACTION); filter.addAction(STOP_AND_SAVE_SLEEP); registerReceiver(serviceReceiver,filter); updateTimer=new Timer(); dateStarted=new Date(); }
Example 42
From project embedmongo.flapdoodle.de, under directory /src/main/java/de/flapdoodle/embedmongo/.
Source file: MongodProcess.java

/** * 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 43
From project freemind, under directory /freemind/accessories/plugins/.
Source file: BlinkingNodeHook.java

public void invoke(MindMapNode node){ super.invoke(node); if (timer == null) { timer=new Timer(); timer.schedule(new TimerColorChanger(),500,500); nodeChanged(getNode()); } }
Example 44
From project Gmote, under directory /gmoteserver/src/org/gmote/server/media/.
Source file: MediaInfoUpdater.java

private void changePollingState(){ if (!clientIsConnected()) { pollingTimer.cancel(); } else if (!shouldPoll()) { pollingTimer.cancel(); } else { pollingTimer.cancel(); pollingTimer=new Timer("MediaInfoTimer"); pollingTimer.schedule(new UpdateTask(),MEDIA_INFO_UPDATE_DELAY,MEDIA_INFO_UPDATE_DELAY); } }
Example 45
From project guj.com.br, under directory /src/br/com/caelum/guj/feeds/.
Source file: Agregator.java

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 46
From project gxa, under directory /atlas-analytics/src/main/java/uk/ac/ebi/gxa/R/.
Source file: BiocepAtlasRFactory.java

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 47
From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/jerklib/util/.
Source file: NickServAuthPlugin.java

private void connectionComplete(IRCEvent e){ authed=false; e.getSession().sayPrivate("nickserv","identify " + pass); final Timer t=new Timer(); t.schedule(new TimerTask(){ public void run(){ if (!authed) { taskComplete(new Boolean(false)); } this.cancel(); t.cancel(); } } ,40000); }
Example 48
From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/datacollection/controller/.
Source file: ChukwaAgentController.java

/** * Registers a new adaptor. Makes no guarantee about success. On failure, to connect to server, will retry <code>numRetries</code> times, every <code>retryInterval</code> milliseconds. * @return the id number of the adaptor, generated by the agent */ public String addByName(String adaptorID,String adaptorName,String type,String params,long offset,long numRetries,long retryInterval){ ChukwaAgentController.Adaptor adaptor=new ChukwaAgentController.Adaptor(adaptorName,type,params,offset); adaptor.id=adaptorID; if (numRetries >= 0) { try { adaptorID=adaptor.register(); if (adaptorID != null) { runningAdaptors.put(adaptorID,adaptor); runningInstanceAdaptors.put(adaptorID,adaptor); } else { System.err.println("Failed to successfully add the adaptor in AgentClient, adaptorID returned by add() was negative."); } } catch ( IOException ioe) { log.warn("AgentClient failed to contact the agent (" + hostname + ":"+ portno+ ")"); log.warn("Scheduling a agent connection retry for adaptor add() in another " + retryInterval + " milliseconds, "+ numRetries+ " retries remaining"); Timer addFileTimer=new Timer(); addFileTimer.schedule(new AddAdaptorTask(adaptorName,type,params,offset,numRetries - 1,retryInterval),retryInterval); } } else { System.err.println("Giving up on connecting to the local agent"); } return adaptorID; }
Example 49
From project hudsontrayapp-plugin, under directory /client-common/src/main/java/org/hudson/trayapp/.
Source file: HudsonTrayApp.java

public void scheduleTimer(int interval,boolean now){ if (timer != null) { timer.cancel(); } timer=new Timer(true); timer.scheduleAtFixedRate(new UpdateTimerTask(),now ? 0l : (long)interval,interval); }
Example 50
From project huiswerk, under directory /print/zxing-1.6/android/src/com/google/zxing/client/android/wifi/.
Source file: Killer.java

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 51
From project ib-ruby, under directory /misc/IBController 2-9-0/src/ibcontroller/.
Source file: LoginFrameHandler.java

private boolean setFieldsAndClick(final Window window){ if (!Utils.setTextField(window,0,TwsListener.getUserName())) return false; if (!Utils.setTextField(window,1,TwsListener.getPassword())) return false; if (!Utils.setCheckBoxSelected(window,"Use/store settings on server",Settings.getBoolean("StoreSettingsOnServer",false))) return false; if (TwsListener.getUserName().length() == 0) { Utils.findTextField(window,0).requestFocus(); return true; } if (TwsListener.getPassword().length() == 0) { Utils.findTextField(window,1).requestFocus(); return true; } if (Utils.findButton(window,"Login") == null) return false; final Timer timer=new Timer(true); timer.schedule(new TimerTask(){ public void run(){ final AtomicBoolean done=new AtomicBoolean(false); do { GuiSynchronousExecutor.instance().execute(new Runnable(){ public void run(){ Utils.clickButton(window,"Login"); done.set(!Utils.isButtonEnabled(window,"Login")); } } ); Utils.pause(500); } while (!done.get()); } } ,10); return true; }
Example 52
From project IOCipherServer, under directory /src/javax/jmdns/impl/.
Source file: JmmDNSImpl.java

/** */ public JmmDNSImpl(){ super(); _networkListeners=Collections.synchronizedSet(new HashSet<NetworkTopologyListener>()); _knownMDNS=new ConcurrentHashMap<InetAddress,JmDNS>(); _services=new ConcurrentHashMap<String,ServiceInfo>(20); _ListenerExecutor=Executors.newSingleThreadExecutor(); _jmDNSExecutor=Executors.newCachedThreadPool(); _timer=new Timer("Multihommed mDNS.Timer",true); (new NetworkChecker(this,NetworkTopologyDiscovery.Factory.getInstance())).start(_timer); }
Example 53
public DNSTaskStarterImpl(JmDNSImpl jmDNSImpl){ super(); _jmDNSImpl=jmDNSImpl; _timer=new Timer("JmDNS(" + _jmDNSImpl.getName() + ").Timer",true); _stateTimer=new Timer("JmDNS(" + _jmDNSImpl.getName() + ").State.Timer",false); }
Example 54
From project java-cas-client, under directory /cas-client-core/src/test/java/org/jasig/cas/client/validation/.
Source file: Cas20ProxyReceivingTicketValidationFilterTests.java

public void testStartsThreadAtStartup() throws Exception { final MethodFlag scheduleMethodFlag=new MethodFlag(); final Cas20ProxyReceivingTicketValidationFilter filter=newCas20ProxyReceivingTicketValidationFilter(); final Timer timer=new Timer(true){ public void schedule( TimerTask task, long delay, long period){ scheduleMethodFlag.setCalled(); } } ; filter.setMillisBetweenCleanUps(1); filter.setProxyGrantingTicketStorage(storage); filter.setTimer(timer); filter.setTimerTask(defaultTimerTask); filter.init(); assertTrue(scheduleMethodFlag.wasCalled()); }
Example 55
From project java-exec, under directory /src/com/thoughtworks/studios/javaexec/.
Source file: ProcessWatcher.java

public void start(){ timer=new Timer(); timer.schedule(new TimerTask(){ public void run(){ process.destroy(); timedOut=true; } } ,timeout); }
Example 56
From project jDcHub, under directory /jdchub-modules/ChatBot/src/main/java/jdchub/module/.
Source file: ChatBot.java

public void start(){ ConfigurationManager configurationManager=ConfigurationManager.getInstance(); timer=new Timer(true); timer.schedule(new ClientCountSaver(),configurationManager.getLong("client_count_delay"),configurationManager.getLong("client_count_repeat_time")); timer.schedule(new ShareSizeSaver(),configurationManager.getLong("share_size_count_delay"),configurationManager.getLong("share_size_count_repeat_time")); }
Example 57
From project JDE-Samples, under directory /com/rim/samples/device/location/gpsdemoadvanced/.
Source file: CoreGPSDiagnosticScreen.java

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 58
From project jetty-project, under directory /jetty-jboss/src/main/java/org/mortbay/j2ee/session/.
Source file: AbstractStore.java

public void start() throws Exception { _log.trace("starting..."); boolean isDaemon=true; _scavenger=new Timer(isDaemon); long delay=_scavengerPeriod + Math.round(Math.random() * _scavengerPeriod); if (_log.isDebugEnabled()) _log.debug("starting distributed scavenger thread...(period: " + delay + " secs)"); _scavenger.scheduleAtFixedRate(new Scavenger(),delay * 1000,_scavengerPeriod * 1000); _log.debug("...distributed scavenger thread started"); _log.trace("...started"); }
Example 59
From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/.
Source file: JsTestDriverServerImpl.java

public void start(){ try { timer=new Timer(true); timer.schedule(new BrowserReaper(capturedBrowsers),browserTimeout * 2,browserTimeout * 2); server.start(); setChanged(); notifyObservers(Event.STARTED); logger.info("Started the JsTD server on {}",port); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 60
From project k-9, under directory /src/com/fsck/k9/helper/power/.
Source file: TracingPowerManager.java

private TracingPowerManager(Context context){ pm=(PowerManager)context.getSystemService(Context.POWER_SERVICE); if (TRACE) { timer=new Timer(); } }
Example 61
From project LanguageSpecCreator, under directory /src/liber/edit/server/.
Source file: LiberServletImpl.java

/** * 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 62
From project lastfm-android, under directory /app/src/fm/last/android/player/.
Source file: RadioPlayerService.java

/** * Constructor, launches timer immediately * @param mode Volume fade mode <code>FADE_IN</code> or <code>FADE_OUT</code> * @param millis Time the fade process should take * @param steps Number of volume gradations within given fade time */ public FadeVolumeTask(int mode,int millis){ this.mMode=mode; this.mSteps=millis / 20; this.onPreExecute(); new Timer().scheduleAtFixedRate(this,0,millis / mSteps); }
Example 63
From project LTE-Simulator, under directory /src/rs/etf/igor/.
Source file: SimulationProgress.java

public SimulationProgress(UI parent){ this.setParentFrame(parent); initComponents(); setLocation(parent.getWidth() / 2 - getWidth() / 2,parent.getHeight() / 2 - getHeight() / 2); myFrame=this; timer=new Timer(); timer.schedule(new Osciloscop(sinusPicture),0,osciloscopeFrequency); super.setResizable(false); simulation=new Simulation(this,parent); simulation.start(); }
Example 64
From project lullaby, under directory /src/net/sileht/lullaby/backend/.
Source file: AmpacheBackend.java

public AmpacheBackend(Context context) throws Exception { super("AmpacheBackend"); mContext=context; prefs=PreferenceManager.getDefaultSharedPreferences(context); System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver"); reader=XMLReaderFactory.createXMLReader(); mTimerPing=new Timer(); setDaemon(true); start(); (new AsyncUIUpdate()).start(); }
Example 65
From project mac, under directory /sunspot/sdk/multihop_common_source/src/com/sun/spot/peripheral/radio/.
Source file: RadiostreamProtocolManager.java

RadiostreamProtocolManager(ILowPan lowpan,IRadioPolicyManager radioPolicyManager){ super(lowpan,radioPolicyManager); routingManager=lowpan.getRoutingManager(); retransScheduler=new Timer(); inputQueue=new Queue(); inputHandler=new InputHandler(); RadioFactory.setAsDaemonThread(inputHandler); inputHandler.start(); }
Example 66
From project maven-t7-plugin, under directory /src/main/java/com/googlecode/t7mp/scanner/.
Source file: Scanner.java

public void start(){ log.info("Starting Scanner ...."); this.timer=new Timer(); this.timer.scheduleAtFixedRate(new ModifiedFileTimerTask(scannerConfiguration.getRootDirectory(),scannerConfiguration.getWebappDirectory(),scannerConfiguration.getEndingsAsList(),log),DEFAULT_DELAY,scannerConfiguration.getInterval() * MILLIS); log.info("Scanner started"); }
Example 67
From project mawLib, under directory /src/mxj/trunk/mawLib-mxj/src/net/christopherbaker/utils/filesystem/.
Source file: DirWatcher.java

public void setInterval(long interval){ this.interval=interval; if (t != null) { t.cancel(); t.purge(); } t=new Timer(); t.scheduleAtFixedRate(this,0,interval); }
Example 68
From project mp3tunes-android, under directory /src/com/mp3tunes/android/service/.
Source file: Mp3tunesService.java

/** * Constructor, launches timer immediately * @param mode Volume fade mode <code>FADE_IN</code> or <code>FADE_OUT</code> * @param millis Time the fade process should take * @param steps Number of volume gradations within given fade time */ public FadeVolumeTask(int mode,int millis){ this.mMode=mode; this.mSteps=millis / 20; this.onPreExecute(); new Timer().scheduleAtFixedRate(this,0,millis / mSteps); }
Example 69
From project MyHeath-Android, under directory /src/com/buaa/shortytall/activity/.
Source file: SplashActivity.java

@Override protected void onCreate(Bundle savedInstanceState){ requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.splash); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); mTimer=new Timer(true); mStartTime=System.currentTimeMillis(); mTimer.schedule(task,0,1); super.onCreate(savedInstanceState); }
Example 70
From project ndg, under directory /ndg-server-core/src/main/java/br/org/indt/ndg/server/sms/.
Source file: NewSMSInFileListener.java

protected NewSMSInFileListener(IObserverSMS observerSMS){ Properties properties=PropertiesUtil.loadFileProperty(PropertiesUtil.PROPERTIES_CORE_FILE); directory=new File(properties.getProperty("SURVEY_ROOT") + "\\Inbox"); register(observerSMS); timer=new Timer(); timer.schedule(new SMSNewListenerInner(),1000,10000); }
Example 71
From project Opal, under directory /discontinued/opal-geo/src/main/java/com/lyndir/lhunath/opal/gui/.
Source file: Splash.java

/** * 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 72
From project org.openscada.atlantis, under directory /org.openscada.da.server.exec/src/org/openscada/da/server/exec/command/.
Source file: CommandQueueImpl.java

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 73
From project PartyWare, under directory /android/src/com/google/zxing/client/android/wifi/.
Source file: Killer.java

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 74
From project Path-Computation-Element-Emulator, under directory /PCEE/src/com/pcee/architecture/sessionmodule/.
Source file: SessionModuleImpl.java

public void start(){ localDebugger("Entering: start()"); stateMachineTimer=new Timer(); addressToStateMachineHashMap=new HashMap<String,StateMachine>(); readingQueueThread=new ReadingQueueThreadImpl[sessionThreads]; for (int i=0; i < sessionThreads; i++) { readingQueueThread[i]=new ReadingQueueThreadImpl(); readingQueueThread[i].setName("SessionLayerThread" + i); readingQueueThread[i].start(); } }
Example 75
From project PDF-to-unusual-HTML, under directory /PDF-to-unusual-HTML/src/com/neumino/pdftounusualhtml/.
Source file: ProcessTimeout.java

public static int exec(String command) throws IOException { Timer timer=null; Process p=null; try { timer=new Timer(true); InterruptTimerTask interrupter=new InterruptTimerTask(Thread.currentThread()); timer.schedule(interrupter,5 * 60 * 1000); p=Runtime.getRuntime().exec(command); int exitVal=p.waitFor(); return exitVal; } catch ( InterruptedException e) { timer.cancel(); p.destroy(); return -2; } finally { timer.cancel(); Thread.interrupted(); } }
Example 76
From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/rhino/.
Source file: ScriptRunner.java

public void markStepInProgress(String stepId,ResultType type){ if (logger.isLoggable(Level.FINER)) { logger.finer("markStepInProgress: stepId=" + stepId + " type="+ type); } if (stepTimer != null) stepTimer.cancel(); inProgress=true; stepTimer=new Timer(); stepTimer.schedule(new StepInProgressMonitor(this,stepId,type),(long)(Configuration.getTimeBetweenStepsOnError() * 1.5)); }
Example 77
From project PermissionsEx, under directory /src/main/java/ru/tehkode/permissions/.
Source file: PermissionManager.java

public void initTimer(){ if (timer != null) { timer.cancel(); } timer=new Timer("PermissionsEx-Cleaner"); }
Example 78
From project Playlist, under directory /src/com/google/zxing/client/android/wifi/.
Source file: Killer.java

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 79
public final synchronized void initialize(){ if (initialized) { return; } fullScreenWidth=getWidth(); fullScreenHeight=getHeight(); loadFont(); loadStatusFont(); final int w=getWidth(); centerBoxSide=Math.min(w,getHeight()) / 8; statusBarHeight=fontStatus.getLineHeight() + (STATUS_BAR_SPACING * 2); AlbiteMIDlet.LOGGER.log("status bar height: " + statusBarHeight); clockWidth=(fontStatusMaxWidth * clockChars.length) + (STATUS_BAR_SPACING * 2); chapterNoWidth=(fontStatusMaxWidth * chapterNoChars.length) + (STATUS_BAR_SPACING * 2); updateProgressBarSize(w); progressBarHeight=(statusBarHeight - (STATUS_BAR_SPACING * 2)) / 3; waitCursor=new ImageButton("/res/gfx/hourglass.ali",TASK_NONE); if (currentScheme == null) { ColorScheme day=ColorScheme.DEFAULT_DAY; ColorScheme night=ColorScheme.DEFAULT_NIGHT; day.link(night); currentScheme=day; } loadButtons(); applyColorProfile(); initializePageCanvases(); applyScrollingSpeed(); applyAbsScrPgOrd(); applyScrollingLimits(); timer=new Timer(); initialized=true; }
Example 80
From project android-context, under directory /src/edu/fsu/cs/contextprovider/.
Source file: ContextAccuracyActivity.java

@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); final PowerManager pm=(PowerManager)getSystemService(Context.POWER_SERVICE); wakelock=pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,"ContextAccuracyActivity"); wakelock.acquire(); KeyguardManager km=(KeyguardManager)getSystemService(KEYGUARD_SERVICE); KeyguardManager.KeyguardLock keylock=km.newKeyguardLock(TAG); keylock.disableKeyguard(); getPrefs(); setContentView(R.layout.accuracy); vibrate=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE); audio=(AudioManager)getSystemService(Context.AUDIO_SERVICE); volume=(AudioManager)getSystemService(Context.AUDIO_SERVICE); placeBar=(SeekBar)findViewById(R.id.place); movementBar=(SeekBar)findViewById(R.id.movement); activityBar=(SeekBar)findViewById(R.id.activity); shelterGroup=(RadioGroup)findViewById(R.id.shelter); shelterCorrect=(RadioButton)findViewById(R.id.shelterCorrect); onPersonGroup=(RadioGroup)findViewById(R.id.onPerson); onPersonCorrect=(RadioButton)findViewById(R.id.onPersonCorrect); placeText=(EditText)findViewById(R.id.editPlace); movementText=(EditText)findViewById(R.id.editMovement); activityText=(EditText)findViewById(R.id.editActivity); shelterText=(EditText)findViewById(R.id.editShelter); onPersonText=(EditText)findViewById(R.id.editOnPerson); placeText.setText(DerivedMonitor.getPlace()); movementText.setText(MovementMonitor.getMovementState()); activityText.setText(DerivedMonitor.getActivity()); shelterText.setText(DerivedMonitor.getShelterString()); onPersonText.setText(DerivedMonitor.getOnPersonString()); submitBtn=(Button)findViewById(R.id.SubmitButton); resetBtn=(Button)findViewById(R.id.ResetButton); submitBtn.setOnClickListener(this); resetBtn.setOnClickListener(this); resetBars(); if (accuracyAudioEnabled) tone.play(); if (accuracyVibrateEnabled) startVibrate(); timer=new Timer(); timer.schedule(new ContextDismissTask(),(dismissDelay * 1000)); }
Example 81
From project android-xbmcremote, under directory /src/org/xbmc/android/remote/presentation/controller/.
Source file: RemoteController.java

public boolean onTouch(View v,MotionEvent event){ if (event.getAction() == MotionEvent.ACTION_DOWN) { Log.d(TAG,"onTouch - ACTION_DOWN"); if (mDoVibrate) { mVibrator.vibrate(VIBRATION_LENGTH); } mEventClientManager.sendButton("R1",mAction,!prefs.getBoolean("setting_send_repeats",false),true,true,(short)0,(byte)0); if (prefs.getBoolean("setting_send_repeats",false) && !prefs.getBoolean("setting_send_single_click",false)) { if (tmrKeyPress != null) { tmrKeyPress.cancel(); } int RepeatDelay=Integer.parseInt(prefs.getString("setting_repeat_rate","250")); tmrKeyPress=new Timer(); tmrKeyPress.schedule(new KeyPressTask(mAction),RepeatDelay,RepeatDelay); } } else if (event.getAction() == MotionEvent.ACTION_UP) { Log.d(TAG,"onTouch - ACTION_UP"); v.playSoundEffect(AudioManager.FX_KEY_CLICK); mEventClientManager.sendButton("R1",mAction,false,false,true,(short)0,(byte)0); if (tmrKeyPress != null) { tmrKeyPress.cancel(); } } return false; }
Example 82
From project Android_1, under directory /Livewallpaper/switch_animation/src/com/novoda/wallpaper/.
Source file: AnimSwitchWallPaper.java

@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 83
public boolean getLocation(Context context,LocationResult result){ locationResult=result; if (lm == null) lm=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); try { gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch ( Exception ex) { } try { network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch ( Exception ex) { } if (!gps_enabled && !network_enabled) return false; if (gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListenerGps); if (network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(),20000); return true; }
Example 84
From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/impl/.
Source file: DefaultSmppServer.java

/** * Creates a new default SmppServer. * @param configuration The server configuration to create this server with * @param serverHandler The handler implementation for handling bind requestsand creating/destroying sessions. * @param executor The executor that IO workers will be executed with. AnExecutors.newCachedDaemonThreadPool() is recommended. The max threads will never grow more than configuration.getMaxConnections() if NIO sockets are used. * @param monitorExecutor The scheduled executor that all sessions will shareto monitor themselves and expire requests. If null monitoring will be disabled. */ public DefaultSmppServer(final SmppServerConfiguration configuration,SmppServerHandler serverHandler,ExecutorService executor,ScheduledExecutorService monitorExecutor){ this.configuration=configuration; this.channels=new DefaultChannelGroup(); this.serverHandler=serverHandler; this.bossThreadPool=Executors.newCachedThreadPool(); if (configuration.isNonBlockingSocketsEnabled()) { this.channelFactory=new NioServerSocketChannelFactory(this.bossThreadPool,executor,configuration.getMaxConnectionSize()); } else { this.channelFactory=new OioServerSocketChannelFactory(this.bossThreadPool,executor); } this.serverBootstrap=new ServerBootstrap(this.channelFactory); this.serverBootstrap.setOption("reuseAddress",configuration.isReuseAddress()); this.serverConnector=new SmppServerConnector(channels,this); this.serverBootstrap.getPipeline().addLast(SmppChannelConstants.PIPELINE_SERVER_CONNECTOR_NAME,this.serverConnector); this.bindTimer=new Timer(configuration.getName() + "-BindTimer0",true); this.transcoder=new DefaultPduTranscoder(new DefaultPduTranscoderContext()); this.sessionIdSequence=new AtomicLong(0); this.monitorExecutor=monitorExecutor; this.counters=new DefaultSmppServerCounters(); if (configuration.isJmxEnabled()) { registerMBean(); } }
Example 85
From project cometd, under directory /cometd-java/cometd-java-server/src/main/java/org/cometd/server/.
Source file: BayeuxServerImpl.java

@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 86
public boolean getLocation(Context context,LocationResult result){ locationResult=result; if (lm == null) lm=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); try { gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch ( Exception ex) { } try { network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch ( Exception ex) { } if (!gps_enabled && !network_enabled) return false; if (gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListenerGps); if (network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(),20000); return true; }
Example 87
private void init(final String url){ commandManager=new CommandManager(this); _mainScreen=new MainScreen(); pushScreen(_mainScreen); loadingImage=EncodedImage.getEncodedImageResource(LOADING_IMAGE); if (loadingImage != null) { loadingField.setImage(loadingImage); loadingScreen.add(loadingField); pushScreen(loadingScreen); } _mainScreen.addKeyListener(new PhoneGapKeyListener(this)); _renderingSession=RenderingSession.getNewInstance(); _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID,RenderingOptions.JAVASCRIPT_ENABLED,true); _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID,RenderingOptions.JAVASCRIPT_LOCATION_ENABLED,true); _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID,17000,true); PrimaryResourceFetchThread thread=new PrimaryResourceFetchThread(url,null,null,null,this); thread.start(); refreshTimer=new Timer(); refreshTimer.scheduleAtFixedRate(new TimerRefresh(),500,500); EventLogger.register(LogCommand.LOG_GUID,LogCommand.APP_NAME,EventLogger.VIEWER_STRING); }
Example 88
From project Diver, under directory /org.eclipse.zest.custom.sequence/src/org/eclipse/zest/custom/sequence/internal/.
Source file: DelayedProgressMonitorDialog.java

public void runInUIThread(final AbstractSimpleProgressRunnable runnable,boolean enableCancelButton) throws InvocationTargetException { setBlockOnOpen(false); if (Display.getCurrent() == null) { throw new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS); } final Display finalDisplay=Display.getCurrent(); this.enableCancelButton=enableCancelButton; create(); this.monitor=new SimpleProgressMonitor(this,enableCancelButton); new Timer("Delayed Progress Service").schedule(new TimerTask(){ public void run(){ finalDisplay.asyncExec(new Runnable(){ public void run(){ if (!(monitor.isCancelled() || monitor.isDone())) { open(); } } } ); } } ,1500); progressIndicator.beginAnimatedTask(); runnable.runInUIThread(monitor); if (isOpenned) { close(); } }
Example 89
From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/util/.
Source file: MyLocation.java

public boolean getLocation(Context context,LocationResult result){ locationResult=result; if (lm == null) lm=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); try { gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch ( Exception ex) { } try { network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch ( Exception ex) { } if (!gps_enabled && !network_enabled) { Toast.makeText(context,"No location provider available, defaulting to Gates Building, Stanford Univesity.",Toast.LENGTH_SHORT).show(); Location l=new Location("yo' mama"); l.setLongitude(-122.179727); l.setLatitude(37.426762); locationResult.gotLocation(l); return false; } if (gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListenerGps); if (network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(),20000); return true; }
Example 90
From project evodroid, under directory /src/com/sonorth/evodroid/util/.
Source file: LocationHelper.java

public boolean getLocation(Context context,LocationResult result){ locationResult=result; if (lm == null) lm=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); try { gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch ( Exception ex) { } try { network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch ( Exception ex) { } if (!gps_enabled && !network_enabled) return false; if (gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListenerGps); if (network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(),30000); return true; }
Example 91
From project FileExplorer, under directory /src/net/micode/fileexplorer/.
Source file: CategoryBar.java

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 92
From project formic, under directory /src/java/org/formic/wizard/form/gui/binding/.
Source file: TextComponentBinding.java

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 93
From project GeekAlarm, under directory /android/src/com/geek_alarm/android/activities/.
Source file: TaskActivity.java

@Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); if (getIntent().getData() == null) { testTask=true; } else if (!containsToday()) { finish(); return; } numberOfAttempts=Utils.getNumberOfAttempts(); positiveBalance=Utils.getPositiveBalance(); inflater=getLayoutInflater(); layout=(LinearLayout)inflater.inflate(R.layout.task,null); setContentView(layout); createPlayer(); choiceListener=new ChoiceListener(); availableTasks=new LinkedList<Task>(); waitingForTask=true; Utils.updateTaskTypesAsync(true); runTaskLoader(); timer=new Timer(); findViewById(R.id.mute_button).setOnClickListener(new MuteListener()); findViewById(R.id.info_button).setOnClickListener(new InfoListener()); updateStats(); curPlayDelay=MuteUtils.getInitialMuteTime() * 1000; }
Example 94
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 95
void HandleGetContactListOpcode(Packet packet) throws Exception { ResultSet rs=Main.db.query("SELECT a.guid, a.username, a.title, a.psm FROM contact AS c LEFT JOIN account AS a ON c.c_guid = a.guid WHERE c.o_guid = %d",c.getGuid()); Packet p; while (rs.next()) { int guid=rs.getInt(1); String username=rs.getString(2); String title=rs.getString(3); String psm=rs.getString(4); Client target=Main.clientList.findClient(rs.getInt(1)); int status=target != null ? target.getStatus() : 3; p=new Packet(SMSG_CONTACT_DETAIL); p.put(guid); p.put(username); p.put(title); p.put(psm); p.put(status); SendPacket(p); System.out.printf("Send Contact: %s to client %d\n",rs.getString(2),c.getGuid()); Thread.sleep(10); } rs.close(); System.out.print("Send Opcode: SMSG_CONTACT_LIST_ENDED\n"); SendPacket(new Packet(SMSG_CONTACT_LIST_ENDED)); System.out.printf("Send contact: Finish\n"); System.out.printf("Send recent contact request to client %d.\n",c.getGuid()); ResultSet requestRS=Main.db.query("SELECT a.guid, a.username FROM contact_request AS c LEFT JOIN account AS a ON c.r_guid = a.guid WHERE c.o_guid = %d",c.getGuid()); while (requestRS.next()) { System.out.printf("Send Contact Request: %s to client %d\n",requestRS.getString(2),c.getGuid()); p=new Packet(SMSG_CONTACT_REQUEST); p.put(requestRS.getInt(1)); p.put(requestRS.getString(2)); SendPacket(p); Thread.sleep(10); } requestRS.close(); timer=new Timer(); timer.schedule(new PeriodicLatencyCheck(),1000); }
Example 96
public JFlowPanel(Configuration config){ super(); this.config=config; listeners=new HashSet<ShapeListener>(); scene=new Scene(new Point3D(0,0,1),new RotationMatrix(0,0,0),new Point3D(0,0,1)); buttonOnePressed=false; dragging=false; shapeArrayOffset=0; activeShape=null; setLayout(null); setBackground(config.backgroundColor); setScrollRate(0); if (config.autoScrollAmount != 0) { new Timer().scheduleAtFixedRate(new AutoScroller(),0,1000 / config.framesPerSecond); } addMouseListener(this); addMouseMotionListener(this); }
Example 97
/** * Initialize everything. * @param address The interface to which JmDNS binds to. * @param name The host name of the interface. */ private void init(InetAddress address,String name) throws IOException { final int idx=name.indexOf("."); if (idx > 0) { name=name.substring(0,idx); } name+=".local."; localHost=new HostInfo(address,name); cache=new DNSCache(100); listeners=Collections.synchronizedList(new ArrayList()); serviceListeners=new HashMap(); typeListeners=new ArrayList(); services=new Hashtable(20); serviceTypes=new Hashtable(20); timer=new Timer(); new RecordReaper(this).start(timer); shutdown=new Thread(new Shutdown(),"JmDNS.Shutdown"); Runtime.getRuntime().addShutdownHook(shutdown); incomingListener=new Thread(new SocketListener(this),"JmDNS.SocketListener"); openMulticastSocket(getLocalHost()); start(getServices().values()); }
Example 98
From project jPOS-EE, under directory /modules/status/src/main/java/org/jpos/ee/status/.
Source file: Monitor.java

public void initService(){ db=new DB(); mgr=new StatusManager(db); timer=new Timer(true); Iterator iter=config.getChildren("monitor").iterator(); List handlers=new ArrayList(); while (iter.hasNext()) { Element e=(Element)iter.next(); try { registerTask(e); } catch ( ConfigurationException ex) { getLog().error(ex); } } }
Example 99
From project jsword, under directory /src/main/java/org/crosswire/common/progress/.
Source file: Job.java

public void beginJob(String sectionName,URI predictURI){ if (finished) { return; } synchronized (this) { currentSectionName=sectionName; predictionMapURI=predictURI; jobMode=ProgressMode.PREDICTIVE; startTime=System.currentTimeMillis(); fakingTimer=new Timer(); fakingTimer.schedule(new PredictTask(),0,REPORTING_INTERVAL); totalUnits=loadPredictions(); if (totalUnits == Progress.UNKNOWN) { totalUnits=EXTRA_TIME; jobMode=ProgressMode.UNKNOWN; } nextPredictionMap=new HashMap<String,Integer>(); } JobManager.fireWorkProgressed(this); }
Example 100
From project madvertise-android-sdk, under directory /madvertiseSDK/src/de/madvertise/android/sdk/.
Source file: MadvertiseView.java

/** * 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 101
From project MimeUtil, under directory /src/main/java/eu/medsea/mimeutil/detector/.
Source file: OpendesktopMimeDetector.java

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 102
From project moho, under directory /moho-sample/Outbound/src/main/java/com/voxeo/moho/sample/.
Source file: Outbound.java

@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 103
From project multibit, under directory /src/main/java/org/multibit/viewsystem/swing/.
Source file: MultiBitFrame.java

@SuppressWarnings("deprecation") public MultiBitFrame(MultiBitController controller){ this.controller=controller; this.model=controller.getModel(); this.localiser=controller.getLocaliser(); this.thisFrame=this; setCursor(Cursor.WAIT_CURSOR); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle(localiser.getString("multiBitFrame.title")); ToolTipManager.sharedInstance().setDismissDelay(TOOLTIP_DISMISSAL_DELAY); final MultiBitController finalController=controller; this.addWindowListener(new WindowAdapter(){ public void windowClosing( WindowEvent arg0){ org.multibit.action.ExitAction exitAction=new org.multibit.action.ExitAction(finalController); exitAction.execute(null); } } ); application=new DefaultApplication(); getContentPane().setBackground(MultiBitFrame.BACKGROUND_COLOR); sizeAndCenter(); normalBorder=BorderFactory.createEmptyBorder(0,4,7,4); underlineBorder=BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(0,4,3,4),BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0,0,1,0,SELECTION_BACKGROUND_COLOR),BorderFactory.createEmptyBorder(0,0,3,0))); initUI(); applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); recreateAllViews(false); nowOffline(); updateStatusLabel(""); estimatedBalanceTextLabel.setText(controller.getLocaliser().bitcoinValueToString4(model.getActiveWalletEstimatedBalance(),true,false)); availableBalanceTextLabel.setText(controller.getLocaliser().getString("multiBitFrame.availableToSpend",new Object[]{controller.getLocaliser().bitcoinValueToString4(model.getActiveWalletAvailableBalance(),true,false)})); estimatedBalanceTextLabel.setFocusable(true); estimatedBalanceTextLabel.requestFocusInWindow(); pack(); setVisible(true); fileChangeTimer=new Timer(); fileChangeTimer.schedule(new FileChangeTimerTask(controller,this),0,60000); }
Example 104
From project mythmote, under directory /src/tkj/android/homecontrol/mythmote/.
Source file: MythCom.java

/** * 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 105
From project nuxeo-tycho-osgi, under directory /nuxeo-runtime/nuxeo-runtime/src/main/java/org/nuxeo/runtime/detection/.
Source file: MulticastDetector.java

public synchronized void start(){ if (heartBeatDetection != null) { return; } try { socket.setSoTimeout((int)heartBeatTimeout); heartBeatDetection=new HeartBeatDetection(); heartBeatDetection.start(); processingTimer=new Timer("Nuxeo.Detection.Cleanup"); processingTimer.schedule(new CleanupTask(),heartBeatTimeout,heartBeatTimeout); socket.joinGroup(groupAddr); heartBeatTimer=new Timer("Nuxeo.Detection.HeartBeat"); heartBeatTimer.schedule(new HeartBeatTask(),0,heartBeatTimeout); } catch ( Throwable t) { stop(); } }
Example 106
From project omid, under directory /src/main/java/com/yahoo/omid/client/.
Source file: TSOClient.java

public TSOClient(Configuration conf) throws IOException { state=State.DISCONNECTED; queuedOps=new ArrayBlockingQueue<Op>(200); retryTimer=new Timer(true); commitCallbacks=Collections.synchronizedMap(new HashMap<Long,CommitCallback>()); isCommittedCallbacks=Collections.synchronizedMap(new HashMap<Long,List<CommitQueryCallback>>()); createCallbacks=new ConcurrentLinkedQueue<CreateCallback>(); channel=null; System.out.println("Starting TSOClient"); factory=new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),3); bootstrap=new ClientBootstrap(factory); int executorThreads=conf.getInt("tso.executor.threads",3); bootstrap.getPipeline().addLast("executor",new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(executorThreads,1024 * 1024,4 * 1024 * 1024))); bootstrap.getPipeline().addLast("handler",this); bootstrap.setOption("tcpNoDelay",false); bootstrap.setOption("keepAlive",true); bootstrap.setOption("reuseAddress",true); bootstrap.setOption("connectTimeoutMillis",100); String host=conf.get("tso.host"); int port=conf.getInt("tso.port",1234); max_retries=conf.getInt("tso.max_retries",100); retry_delay_ms=conf.getInt("tso.retry_delay_ms",1000); if (host == null) { throw new IOException("tso.host missing from configuration"); } addr=new InetSocketAddress(host,port); connectIfNeeded(); }
Example 107
From project onebusaway-android, under directory /src/com/joulespersecond/seattlebusbot/.
Source file: MySearchFragmentBase.java

@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 108
From project pegadi, under directory /client/src/main/java/org/pegadi/artis/.
Source file: Artis.java

public void startAutoSaver(){ if (autoSaveTimer != null) { autoSaveTimer.cancel(); } Integer savePeriodMinutes; try { savePeriodMinutes=Integer.parseInt(preferences.getProperty(ArtisPrefsDialog.AUTO_SAVE_PREF)); } catch ( NumberFormatException e) { log.debug("No preference found for autoSave"); savePeriodMinutes=10; } long savePeriod=(1000 * 60) * savePeriodMinutes; autoSaveTimer=new Timer(); autoSaveTimer.scheduleAtFixedRate(new AutoSaver(),savePeriod,savePeriod); }
Example 109
From project platform_packages_apps_settings, under directory /src/com/android/settings/wifi/.
Source file: WpsDialog.java

@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 110
From project pluto, under directory /pluto-container-driver-api/src/main/java/org/apache/pluto/container/driver/.
Source file: PortletServlet.java

/** * 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 111
From project Gemini-Blueprint, under directory /extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/.
Source file: ExtenderConfiguration.java

private TaskExecutor createDefaultShutdownTaskExecutor(){ TimerTaskExecutor taskExecutor=new TimerTaskExecutor(){ @Override protected Timer createTimer(){ return new Timer("Gemini Blueprint context shutdown thread",true); } } ; taskExecutor.afterPropertiesSet(); isShutdownTaskExecutorManagedInternally=true; return taskExecutor; }
Example 112
From project leviathan, under directory /common/src/main/java/ar/com/zauber/leviathan/common/async/.
Source file: JobScheduler.java

/** * Creates the FetcherScheduler. */ public JobScheduler(final JobQueue<Job> queue,final ExecutorService executorService,final Timer timer,final long timeout){ super(queue); Validate.notNull(queue); Validate.notNull(executorService); if (timer != null) { Validate.isTrue(timeout > 0); } this.executorService=executorService; this.timer=timer; this.timeout=timeout; }
Example 113
From project moji, under directory /src/main/java/fm/last/moji/tracker/pool/.
Source file: ManagedTrackerHost.java

ManagedTrackerHost(InetSocketAddress address,Timer resetTimer,Clock clock){ lastUsed=new AtomicLong(); lastFailed=new AtomicLong(); hostRetryInterval=1; hostRetryIntervalTimeUnit=MINUTES; this.resetTimer=resetTimer; resetTaskFactory=new ResetTaskFactory(); this.clock=clock; this.address=address; }