List of usage examples for java.util Timer scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
From source file:com.vmware.identity.session.TomcatAccessLogCleaner.java
/** * Perform clean up of the tomcat access log files *///from w ww.j a va2 s.com public void startLogCleaningProcess(File accessLogDirectory) { logger.info("Cleaning up tomcat access log files under : {}", accessLogDirectory.getAbsolutePath()); Timer timer = new Timer(IS_DAEMON); AccessLogCleanerTask tomcatAccessLogCleaner = new AccessLogCleanerTask(accessLogDirectory); logger.info("Starting to schedule the log clean up tasks.."); timer.scheduleAtFixedRate(tomcatAccessLogCleaner, 0, TIMER_TASK_DELAY_IN_MILLIS); }
From source file:org.gdgsp.fragment.PeopleFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_random: // Se o tamanho da lista for maior que 0 significa que j carregou if (selectedList.size() > 0) { // Aqui vai gerar um nmero aleatrio entre 0 e o tamanho da lista - 1 Random random = new Random(); int number = random.nextInt(selectedList.size()); // Aps isso o aplicativo vai dar scroll e exibir a pessoa na posio do nmero aleatrio ((LinearLayoutManager) list.getLayoutManager()).scrollToPositionWithOffset(number, 0); if (person != null && selectedList.get(number).getId() == person.getId()) { count = 0;/*from ww w . j a v a 2s .c o m*/ // Verifica o tanto de tempo que a pessoa ficou com o alerta aberto, se demorar muito vai ter coisa errada, como mudar a hora do sistema e aguardar o sorteio final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { count++; } }, 1000, 1000); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy"); String localDate = sdf.format(new Date()); SimpleDateFormat dbDateSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final String dbDate = dbDateSDF.format(new Date()); AlertDialog alertDialog = new AlertDialog.Builder(activity) .setTitle(getString(R.string.raffle_person)) .setMessage("Voc!\n\nSorteado s " + localDate) .setPositiveButton(getString(R.string.send), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface p1, int p2) { timer.cancel(); sendRaffle(dbDate); } }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface p1, int p2) { timer.cancel(); } }) .create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); } else { AlertDialog alertDialog = new AlertDialog.Builder(activity) .setTitle(getString(R.string.raffle_person)) .setMessage(selectedList.get(number).getName()).setPositiveButton("OK", null).create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); } } return true; case R.id.menu_hasapp: // Exibir apenas pessoas que usam o aplicativo, essa informao vem de um banco de dados no back-end item.setChecked(!item.isChecked()); selectedList.clear(); selectedList.addAll(item.isChecked() ? hasAppPeople : listPeople); adapter.notifyDataSetChanged(); return true; default: return super.onOptionsItemSelected(item); } }
From source file:ota.otaupdates.Settings.java
@Override public void onCreate(Bundle savedInstanceState) { if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false)) setTheme(R.style.AppTheme_Light); else//from ww w . j a v a2 s .c o m setTheme(R.style.AppTheme_Dark); super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); SwitchPreference enable_auto_install = (SwitchPreference) findPreference("enable_auto_install"); if (!Shell.SU.available()) { enable_auto_install.setEnabled(false); enable_auto_install.setChecked(false); enable_auto_install.setSummary(getString(R.string.auto_install_root_only)); } final SwitchPreference setEnglish = (SwitchPreference) findPreference("force_english"); setEnglish.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this); if (MainActivity.sharedPreferences.getBoolean("force_english", false)) builder.setTitle(getString(R.string.force_english_window_title)); else builder.setTitle(getString(R.string.force_default_window_title)); builder.setMessage(getString(R.string.force_english_window_message)); builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }); builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alert = builder.create(); alert.setCancelable(true); alert.show(); return true; } }); SwitchPreference apptheme_light = (SwitchPreference) findPreference("apptheme_light"); apptheme_light.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this); if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false)) setTheme(R.style.AppTheme_Light); else setTheme(R.style.AppTheme_Dark); builder.setMessage(getString(R.string.switch_apptheme_light_window_message)); builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }); builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alert = builder.create(); alert.setCancelable(true); alert.show(); return true; } }); findPreference("clean_junk").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (Build.VERSION.SDK_INT >= 23 && !checkPermission()) { // If user hasn't allowed yet, request the permission. requestPermission(); } final AlertDialog.Builder delete_dialog = new AlertDialog.Builder(Settings.this); delete_dialog.setMessage(R.string.clean_junk_dialog_summary); delete_dialog.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { File folder = new File(Utils.DL_PATH); File fList[] = folder.listFiles(); if (fList != null) { for (i = 0; i < fList.length; i++) { String pes = String.valueOf(fList[i]); if (pes.endsWith(".zip")) { fList[i].delete(); } } } Log.d(getString(R.string.app_name) + ": clean_junk", "Old files cleaned"); Toast.makeText(getApplicationContext(), R.string.clean_junk_toast, Toast.LENGTH_SHORT) .show(); } }); delete_dialog.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); delete_dialog.show(); return true; } }); findPreference("devs").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clickcount++; switch (clickcount) { case 8: case 12: case 16: case 20: case 24: Toast.makeText(getApplicationContext(), R.string.crash_soon, Toast.LENGTH_SHORT).show(); break; case 28: Toast.makeText(getApplicationContext(), R.string.crash_soon_really, Toast.LENGTH_SHORT).show(); final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { clickcount = 0; Toast.makeText(getApplicationContext(), R.string.crash_soon_gaveup, Toast.LENGTH_SHORT).show(); } }); timer.cancel(); } }, 4000, 1); break; case 35: throw new NullPointerException("Well, you pointed at something..."); } return true; } }); }
From source file:ubc.pavlab.aspiredb.server.biomartquery.BioMartQueryServiceImpl.java
private void updateCache() throws BioMartServiceException { /**//from w w w . ja v a 2s . c o m * Commented out code to check if cache hasExpired() because it takes ~8-10ms everytime this method is called. * Assuming cache never expires. */ // if ( this.bioMartCache.hasExpired() ) { if (geneCache == null) { Dataset dataset = new Dataset("hsapiens_gene_ensembl"); dataset.Filter.add( new Filter("chromosome_name", "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y")); dataset.Attribute.add(new Attribute("ensembl_gene_id")); dataset.Attribute.add(new Attribute("hgnc_symbol")); dataset.Attribute.add(new Attribute("description")); dataset.Attribute.add(new Attribute("gene_biotype")); dataset.Attribute.add(new Attribute("chromosome_name")); dataset.Attribute.add(new Attribute("start")); dataset.Attribute.add(new Attribute("end")); Query query = new Query(); query.Dataset = dataset; StringWriter xmlQueryWriter = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Query.class, Dataset.class, Filter.class, Attribute.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); xmlQueryWriter = new StringWriter(); jaxbMarshaller.marshal(query, xmlQueryWriter); } catch (JAXBException e) { String errorMessage = "Cannot initialize genes from BioMart"; log.error(errorMessage, e); throw new BioMartServiceException(errorMessage); } final StopWatch timer = new StopWatch(); timer.start(); Timer uploadCheckerTimer = new Timer(true); uploadCheckerTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { log.info("Waiting for BioMart response ... " + timer.getTime() + " ms"); } }, 0, 100 * 1000); String response = sendRequest(xmlQueryWriter.toString()); uploadCheckerTimer.cancel(); String[] rows = StringUtils.split(response, "\n"); Collection<GeneValueObject> genes = new HashSet<GeneValueObject>(); int rowsLength = rows.length; if (rowsLength <= 1) { String errorMessage = "Error: retrieved only " + rowsLength + " row of gene data from BioMart" + (rowsLength == 1 ? "(Error message from BioMart: " + rows[0] + ")" : ""); log.error(errorMessage); throw new BioMartServiceException(errorMessage); } geneCache = new HashMap<>(rowsLength); for (String row : rows) { String[] fields = row.split("\t"); int index = 0; String ensemblId = fields[index++]; String symbol = fields[index++]; String name = fields[index++]; String geneBiotype = fields[index++]; String chromosome = fields[index++]; String start = fields[index++]; String end = fields[index++]; // Ignore results that do not have required attributes. if (ensemblId.equals("") || symbol.equals("") || chromosome.equals("") || start.equals("") || end.equals("")) { continue; } int sourceIndex = name.indexOf(" [Source:"); name = sourceIndex >= 0 ? name.substring(0, sourceIndex) : name; GeneValueObject gene = new GeneValueObject(ensemblId, symbol, name, geneBiotype, "human"); int startBase = Integer.valueOf(start); int endBase = Integer.valueOf(end); if (startBase < endBase) { gene.setGenomicRange(new GenomicRange(chromosome, startBase, endBase)); } else { gene.setGenomicRange(new GenomicRange(chromosome, endBase, startBase)); } // organize genes by bin, this is for performance reasons, see Bug 4210 int bin = gene.getGenomicRange().getBin(); if (!geneCache.containsKey(bin)) { geneCache.put(bin, new HashSet<GeneValueObject>()); } geneCache.get(bin).add(gene); genes.add(gene); } this.bioMartCache.putAll(genes); log.info("BioMart request to (" + BIO_MART_URL + ") took " + timer.getTime() + " ms and loaded " + genes.size() + " genes"); } }
From source file:kr.co.generic.wifianalyzer.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { MainContext mainContext = MainContext.INSTANCE; mainContext.initialize(this, isLargeScreenLayout()); Settings settings = mainContext.getSettings(); settings.initializeDefaultValues();//from w w w. j av a 2 s .c o m setCurrentThemeStyle(settings.getThemeStyle()); setCurrentAccessPointView(settings.getAccessPointView()); setTheme(getCurrentThemeStyle().themeAppCompatStyle()); setWiFiChannelPairs(); super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); settings.registerOnSharedPreferenceChangeListener(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setOnClickListener(new WiFiBandToggle()); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); startNavigationMenu = settings.getStartMenu(); navigationMenuView = new NavigationMenuView(this, startNavigationMenu); onNavigationItemSelected(navigationMenuView.getCurrentMenuItem()); connectionView = new ConnectionView(this); Scanner scanner = mainContext.getScanner(); scanner.register(connectionView); HoonProperty.DevicesUUID = Utils.GetDevicesUUID(getApplicationContext()); HoonProperty.AppNM = "WiFi"; AdRequest adRequest = new AdRequest.Builder().build(); adView = (AdView) findViewById(R.id.adView); adView.loadAd(adRequest); TimerTask ts = new TimerTask() { @Override public void run() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { if (um != null) um.cancel(true); um = new UserMonitor(); um.init("user", "", "", HoonProperty.bActive); um.execute(); } }); } }; Timer tm = new Timer(); // tm.scheduleAtFixedRate(ts, 0, 1000 * 30); tm.scheduleAtFixedRate(ts, 0, 1000 * 60); }
From source file:ezbake.frack.common.workers.ProvenanceBatchWorker.java
/** * Initializes the worker with configuration and actions needed prior to * processing./*from w ww. j ava 2 s .c o m*/ * * @param properties The application properties associated with the * environment. */ public void initialize(Properties properties) { EzProperties ezProps = new EzProperties(properties, true); this.outputDuplicates = ezProps.getBoolean(OUTPUT_DUPLICATES_KEY, false); this.maxQueueSize = ezProps.getInteger(BATCH_SIZE_KEY, 50); this.pool = new ThriftClientPool(properties); this.securityClient = new EzbakeSecurityClient(properties); addDocumentEntrySet = Sets.newHashSet(); ageOffMappingSet = Sets.newHashSet(); uriToObjectMap = Maps.newHashMap(); Timer batchWriterTimer = new Timer(); period = Long.valueOf(properties.getProperty(BATCH_TIMEOUT_KEY, String.valueOf(15000))); batchWriterTimer.scheduleAtFixedRate(new ProvenanceBatchTask(), 0, period); logger.info("Creating ProvenanceBatchWorker with max queue size of: {}", maxQueueSize); }
From source file:password.pwm.util.localdb.LocalDBUtility.java
private void importLocalDB(final InputStream inputStream, final Appendable out, final long totalBytes) throws PwmOperationalException, IOException { this.prepareForImport(); importLineCounter = 0;/* w w w . ja v a 2s . c o m*/ if (totalBytes > 0) { writeStringToOut(out, "total bytes in localdb import source: " + totalBytes); } writeStringToOut(out, "beginning localdb import..."); final Instant startTime = Instant.now(); final TransactionSizeCalculator transactionCalculator = new TransactionSizeCalculator( new TransactionSizeCalculator.SettingsBuilder() .setDurationGoal(new TimeDuration(100, TimeUnit.MILLISECONDS)).setMinTransactions(50) .setMaxTransactions(5 * 1000).createSettings()); final Map<LocalDB.DB, Map<String, String>> transactionMap = new HashMap<>(); for (final LocalDB.DB loopDB : LocalDB.DB.values()) { transactionMap.put(loopDB, new TreeMap<>()); } final CountingInputStream countingInputStream = new CountingInputStream(inputStream); final EventRateMeter eventRateMeter = new EventRateMeter(TimeDuration.MINUTE); final Timer statTimer = new Timer(true); statTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { String output = ""; if (totalBytes > 0) { final ProgressInfo progressInfo = new ProgressInfo(startTime, totalBytes, countingInputStream.getByteCount()); output += progressInfo.debugOutput(); } else { output += "recordsImported=" + importLineCounter; } output += ", avgTransactionSize=" + transactionCalculator.getTransactionSize() + ", recordsPerMinute=" + eventRateMeter.readEventRate().setScale(2, BigDecimal.ROUND_DOWN); writeStringToOut(out, output); } }, 30 * 1000, 30 * 1000); Reader csvReader = null; try { csvReader = new InputStreamReader(new GZIPInputStream(countingInputStream, GZIP_BUFFER_SIZE), PwmConstants.DEFAULT_CHARSET); for (final CSVRecord record : PwmConstants.DEFAULT_CSV_FORMAT.parse(csvReader)) { importLineCounter++; eventRateMeter.markEvents(1); final String dbName_recordStr = record.get(0); final LocalDB.DB db = JavaHelper.readEnumFromString(LocalDB.DB.class, null, dbName_recordStr); final String key = record.get(1); final String value = record.get(2); if (db == null) { writeStringToOut(out, "ignoring localdb import record #" + importLineCounter + ", invalid DB name '" + dbName_recordStr + "'"); } else { transactionMap.get(db).put(key, value); int cachedTransactions = 0; for (final LocalDB.DB loopDB : LocalDB.DB.values()) { cachedTransactions += transactionMap.get(loopDB).size(); } if (cachedTransactions >= transactionCalculator.getTransactionSize()) { final long startTxnTime = System.currentTimeMillis(); for (final LocalDB.DB loopDB : LocalDB.DB.values()) { localDB.putAll(loopDB, transactionMap.get(loopDB)); transactionMap.get(loopDB).clear(); } transactionCalculator.recordLastTransactionDuration(TimeDuration.fromCurrent(startTxnTime)); } } } } finally { LOGGER.trace("import process completed"); statTimer.cancel(); IOUtils.closeQuietly(csvReader); IOUtils.closeQuietly(countingInputStream); } for (final LocalDB.DB loopDB : LocalDB.DB.values()) { localDB.putAll(loopDB, transactionMap.get(loopDB)); transactionMap.get(loopDB).clear(); } this.markImportComplete(); writeStringToOut(out, "restore complete, restored " + importLineCounter + " records in " + TimeDuration.fromCurrent(startTime).asLongString()); statTimer.cancel(); }
From source file:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java
/** * Starts the heartbeat./*w w w. jav a 2 s . c o m*/ * * @param websocket The websocket the heartbeat should be sent to. * @param heartbeatInterval The heartbeat interval. * @return The timer used for the heartbeat. */ private Timer startHeartbeat(final WebSocket websocket, final int heartbeatInterval) { final Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { /* if (heartbeatAckReceived) { temporally removed */ heartbeatAckReceived = false; sendHeartbeat(websocket); logger.debug("Sent heartbeat (interval: {})", heartbeatInterval); /*} else { logger.info("We did not receive an answer to our last heartbeat. Trying to reconnect!"); websocket.sendClose(1002); }*/ } }, 0, heartbeatInterval); return timer; }
From source file:org.punksearch.crawler.NetworkCrawler.java
private void startTimers() { Timer processTimer = new Timer(); processTimer.schedule(new MaxRunWatchDog(), maxHours * 3600 * 1000L); Timer statusDumpTimer = new Timer(); long dumpPeriod = Long.getLong(DUMP_STATUS_PERIOD, 10L) * 1000; statusDumpTimer.scheduleAtFixedRate(new ThreadStatusDump(), dumpPeriod, dumpPeriod); timers.add(processTimer);/* www . j a va2 s. com*/ timers.add(statusDumpTimer); }
From source file:com.github.safrain.remotegsh.server.RgshFilter.java
@Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter("charset") != null) { charset = filterConfig.getInitParameter("charset"); } else {/*w w w . java 2 s .c o m*/ charset = DEFAULT_CHARSET; } if (filterConfig.getInitParameter("shellSessionTimeout") != null) { shellSessionTimeout = Long.valueOf(filterConfig.getInitParameter("shellSessionTimeout")); } else { shellSessionTimeout = SESSION_PURGE_INTERVAL; } String scriptExtensionCharset; if (filterConfig.getInitParameter("scriptExtensionCharset") != null) { scriptExtensionCharset = filterConfig.getInitParameter("scriptExtensionCharset"); } else { scriptExtensionCharset = DEFAULT_CHARSET; } //Compile script extensions List<String> scriptExtensionPaths = new ArrayList<String>(); if (filterConfig.getInitParameter("scriptExtensions") != null) { Collections.addAll(scriptExtensionPaths, filterConfig.getInitParameter("scriptExtensions").split(",")); } else { scriptExtensionPaths.add(RESOURCE_PATH + "extension/spring.groovy"); } scriptExtensions = new HashMap<String, CompiledScript>(); for (String path : scriptExtensionPaths) { String scriptContent; try { scriptContent = getResource(path, scriptExtensionCharset); } catch (IOException e) { throw new ServletException(e); } Compilable compilable = (Compilable) createGroovyEngine(); try { CompiledScript compiledScript = compilable.compile(scriptContent); scriptExtensions.put(path, compiledScript); } catch (ScriptException e) { //Ignore exceptions while compiling script extensions,there may be compilation errors due to missing dependency log.log(Level.WARNING, String.format("Error compiling script extension '%s'", path), e); } } // Setup a timer to purge timeout shell sessions Timer timer = new Timer("Remote Groovy Shell session purge daemon", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { purgeTimeOutSessions(); } }, 0, SESSION_PURGE_INTERVAL); }