Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

In this page you can find the example usage for java.util Timer Timer.

Prototype

public Timer() 

Source Link

Document

Creates a new timer.

Usage

From source file:com.makotosan.vimeodroid.ManageTransfersActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.managetransferslayout);

    registerForContextMenu(getListView());
    // Initialize timer
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override//from www.j  av a 2  s .com
        public void run() {
            handler.post(updateList);
            if (StaticInstances.transfers.isEmpty()) {
                this.cancel();
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        }
    };

    timer.scheduleAtFixedRate(task, 0, 3000);
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

public OxfordAuthentication(String clientId, String clientSecret) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    /*//  w ww  .ja  v  a  2s.  c  o m
     * If clientid or client secret has special characters, encode before sending request
     */
    try {
        this.request = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s",
                URLEncoder.encode(clientId, charsetName), URLEncoder.encode(clientSecret, charsetName),
                URLEncoder.encode("https://speech.platform.bing.com", charsetName));

    } catch (Exception e) {
        e.printStackTrace();
    }

    Thread th = new Thread(new Runnable() {
        @Override
        public void run() {
            RenewAccessToken();
        }
    });

    try {
        th.start();
        th.join();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // renew the token every specified minutes
    accessTokenRenewer = new Timer();
    nineMinitesTask = new TimerTask() {
        public void run() {
            RenewAccessToken();
        }
    };

    accessTokenRenewer.schedule(nineMinitesTask, RefreshTokenDuration, RefreshTokenDuration);
}

From source file:TimerMIDlet.java

public void startApp() throws MIDletStateChangeException {

    display = Display.getDisplay(this);
    menu = new List("Stock Menu", Choice.IMPLICIT);
    menu.append("Updates", null);
    menu.append("Add Stocks", null);
    menu.append("Remove Stocks", null);
    menu.addCommand(exitCommand);/*  w  w w  .j a  va  2 s . co m*/
    menu.setCommandListener(this);
    // Make the ticker
    stockTicker = new Ticker(makeTickerString());
    menu.setTicker(stockTicker);

    display.setCurrent(menu);
    _currentMenu = "Stock Menu";

    _updatesForm = new Form("Updates");
    _updatesChoices = new ChoiceGroup("Update Interval:", Choice.EXCLUSIVE);
    _updatesChoices.append("Continuous", null); // will be 10 seconds
    _updatesChoices.append("15 minutes", null);
    _updatesChoices.append("30 minutes", null);
    _updatesChoices.append("1 hour", null);
    _updatesChoices.append("3 hours", null);

    _updatesForm.setTicker(stockTicker);
    _updatesForm.append(_updatesChoices);
    _updatesForm.addCommand(backCommand);
    _updatesForm.addCommand(doneCommand);
    _updatesForm.setCommandListener(this);

    //Set up and start the timer to refresh the stock quotes
    stockRefreshTask = new StockRefreshTask();
    stockRefresh = new Timer();
    stockRefresh.schedule(stockRefreshTask, 0, refresh_interval);
}

From source file:de.blizzy.backup.BackupApplication.java

@Override
public Object start(IApplicationContext context) {
    display = Display.getDefault();//from w w  w.jav a 2 s  . c  om

    boolean restartNecessary = false;

    File runLockFile = new File(BackupPlugin.getDefault().getStateLocation().toFile(), "runLock"); //$NON-NLS-1$
    RunLock runLock = new RunLock(runLockFile);
    if (runLock.tryLock()) {
        setupDefaultPreferences();

        Image image16 = AbstractUIPlugin.imageDescriptorFromPlugin(BackupPlugin.ID, "etc/logo/logo_16.png") //$NON-NLS-1$
                .createImage(display);
        Image image32 = AbstractUIPlugin.imageDescriptorFromPlugin(BackupPlugin.ID, "etc/logo/logo_32.png") //$NON-NLS-1$
                .createImage(display);
        Image image48 = AbstractUIPlugin.imageDescriptorFromPlugin(BackupPlugin.ID, "etc/logo/logo_48.png") //$NON-NLS-1$
                .createImage(display);
        windowImages = new Image[] { image16, image32, image48 };

        settingsManager = new SettingsManager();
        settingsManager.addListener(new ISettingsListener() {
            @Override
            public void settingsChanged() {
                if (backupRun == null) {
                    scheduleBackupRun(false);
                }
            }
        });

        timer = new Timer();

        scheduleBackupRun(false);

        trayIcon = new TrayIcon(display);

        context.applicationRunning();

        if (!BackupPlugin.getDefault().isHidden()) {
            showShell();
        }

        try {
            Shell shell = (backupShell != null) ? backupShell.getShell() : null;
            if (new Updater(false, false).update(shell)) {
                running = false;
                restartNecessary = true;
            }
        } catch (Throwable e) {
            BackupPlugin.getDefault().logError("error while updating application", e); //$NON-NLS-1$
        }

        while (running && !display.isDisposed()) {
            try {
                if (!display.readAndDispatch()) {
                    display.sleep();
                }
            } catch (RuntimeException e) {
                BackupPlugin.getDefault().logError("error in event loop", e); //$NON-NLS-1$
            }
        }

        trayIcon.dispose();

        timer.cancel();
        timer = null;

        image16.dispose();
        image32.dispose();
        image48.dispose();

        if (backupRun != null) {
            backupRun.stopBackupAndWait();
        }
    } else {
        new MessageDialog(null, Messages.Title_ProgramRunning, null, Messages.ProgramRunning,
                MessageDialog.ERROR, new String[] { IDialogConstants.CLOSE_LABEL }, 0).open();
    }

    return restartNecessary ? EXIT_RESTART : EXIT_OK;
}

From source file:deincraftlauncher.start.StartMinecraft.java

private static void checkAlive(Process launch, Modpack pack) {

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override//from w  ww  .  j  a va  2  s  .  co  m
        public void run() {
            if (!launch.isAlive()) {
                Platform.runLater(() -> {
                    System.out.println("minecraft stopped, process is dead!");
                    pack.setPackstarted(false);
                    pack.setStartState(PackViewHandler.StartState.Normal);
                    pack.setStartText("Spielen");
                });
            } else {
                checkAlive(launch, pack);
            }
        }
    }, 3000);
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

@Override
public void init() throws ServletException {
    super.init();

    this.listTemplate = Util.parseStream(getClass().getResourceAsStream("index-template.html"));
    this.groupTemplate = Util.parseStream(getClass().getResourceAsStream("group-template.html"));

    this.properties = new Properties();
    InputStream is = getClass().getResourceAsStream("/config.properties");
    if (is == null) {
        is = getClass().getResourceAsStream("/config.properties.default");
    }//  w  w w .  ja v a  2  s.  c om
    try {
        this.properties.load(is);
    } catch (IOException e1) {
        logger.warn(e1.getMessage(), e1);
        throw new ServletException("Could not init properties!", e1);
    }

    initializeCrawlers();

    readCrawlingLinks();

    String preferredDatabaseLocation = properties.getProperty("DATABASE_DIR");
    storage = new H2Storage(preferredDatabaseLocation);

    this.timer = new Timer();

    Integer crawlPeriod = Util.getIntegerProperty(this.properties, "crawlPeriodHours", 6);
    logger.info(String.format("Scheduling crawl every %s hours.", crawlPeriod));

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            logger.info("Starting to parse ad entries...");
            DateTime now = new DateTime();

            int insertedCount = 0;
            int crawlerCount = 0;

            try {
                for (String baseLink : crawlLinks) {
                    logger.info("Baselink = " + baseLink);

                    Crawler crawler;
                    try {
                        crawler = resolveCrawler(baseLink);
                    } catch (UnsupportedBaseLinkException e1) {
                        logger.warn(e1.getMessage(), e1);
                        break;
                    }

                    crawlerCount++;

                    String link;
                    int page = crawler.getFirstPageIndex();
                    while (true) {
                        Thread.sleep(1000);
                        logger.info("Parsing page " + page);

                        link = crawler.prepareLinkForPage(baseLink, page);
                        HttpGet get = new HttpGet(link);
                        page++;

                        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(
                                RequestConfig.custom().setConnectTimeout(20000).build()).build();
                        try {
                            CloseableHttpResponse resp = client.execute(get);
                            if (resp.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES) {
                                InputStream content = resp.getEntity().getContent();

                                List<Ad> items = parse(content, crawler);
                                if (items == null || items.size() == 0) {
                                    break;
                                }

                                insertedCount += compareAndStoreItems(items, now);

                            } else {
                                break;
                            }
                        } catch (IOException | CrawlerException e) {
                            logger.warn(e.getMessage(), e);
                            Metadata md = new Metadata("Exception during crawl: " + e.getMessage());
                            storage.updateMetadata(md);
                            break;
                        }

                    }

                    logger.info("finished parsing ad entries!");
                }

                Metadata md = new Metadata(String.format("Added %s new entries. %s crawlers have been used",
                        insertedCount, crawlerCount));
                storage.updateMetadata(md);
            } catch (RuntimeException | InterruptedException e) {
                logger.warn(e.getMessage(), e);

                Metadata md = new Metadata("Exception during crawl: " + e.getMessage());
                storage.updateMetadata(md);
            }

        }
    }, 0, 1000 * 60 * 60 * crawlPeriod);
}

From source file:com.connectsdk.discovery.provider.SSDPDiscoveryProvider.java

@Override
public void start() {
    stop();/*from ww  w .  j a  v a 2 s .c  o  m*/

    openSocket();

    dataTimer = new Timer();
    dataTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            sendSearch();
        }
    }, 100, RESCAN_INTERVAL);

    responseThread = new Thread(mResponseHandler);
    notifyThread = new Thread(mRespNotifyHandler);

    responseThread.start();
    notifyThread.start();
}

From source file:net.sf.taverna.t2.reference.ReferenceServiceTest.java

@Test
/**/*from  w ww . j  a v a 2 s. co m*/
 * Test multiple concurrent read / write cycles to the database, producing
 * some rather informal profiling information at the end.
 */
public void testSaturatedReadWriteCycle() throws MalformedURLException {
    int concurrentThreads = 5;
    final int jobsPerThread = 200;
    int joinPoints = 5;
    final URL testUrl = new URL("http://www.ebi.ac.uk/~tmo/patterns.xml");
    ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
            "referenceServiceTestContext.xml");
    //      ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
    //      "inMemoryReferenceServiceTestContext.xml");
    final ReferenceService rs = (ReferenceService) context.getBean("t2reference.service.referenceService");
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private int lastCount = getCount();
        private long lastTime = System.currentTimeMillis();

        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            long interval = currentTime - lastTime;
            lastTime = currentTime;
            int newCount = getCount();
            long jobsProcessed = (long) (newCount - lastCount);
            lastCount = newCount;
            if (interval == 0) {
                System.out.println("(infinity) " + jobsProcessed);
            } else {
                System.out.println((int) (jobsProcessed * 1000 / interval));
            }
        }
    }, 1000, 1000);
    long testStartTime = System.currentTimeMillis();
    for (int i = 0; i < joinPoints; i++) {
        Thread[] threads = new Thread[concurrentThreads];
        for (int j = 0; j < concurrentThreads; j++) {
            threads[j] = new Thread() {
                @Override
                public void run() {
                    for (int k = 0; k < jobsPerThread; k++) {
                        try {
                            //                        T2Reference ref = rs.register("test", 0, true,
                            //                              dummyContext);
                            T2Reference ref = rs.register(testUrl, 0, true, dummyContext);
                            @SuppressWarnings("unused")
                            ReferenceSet refSet = (ReferenceSet) rs.resolveIdentifier(ref, null, dummyContext);
                            incrementRequestsProcessed();
                        } catch (ReferenceServiceException rse) {
                            System.out.println(rse);
                        }
                    }
                }
            };
            threads[j].start();
        }
        for (int j = 0; j < concurrentThreads; j++) {
            try {
                threads[j].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    timer.cancel();
    System.out.println("Test completed, using " + concurrentThreads + " threads, " + getCount() + " at "
            + (long) ((getCount() * 1000) / (System.currentTimeMillis() - testStartTime))
            + " jobs per second averaged over test run");
    System.out.println((System.currentTimeMillis() - testStartTime));
    System.out.println((System.currentTimeMillis() - testStartTime) / (float) (jobsPerThread * joinPoints));
}

From source file:com.mellanox.hadoop.mapred.UdaPlugin.java

protected void launchCppSide(boolean isNetMerger, UdaCallable _callable) {

    //only if this is the provider, start the periodic log check task.
    if (!isNetMerger) {
        LOG.debug("starting periodic log check task");
        Timer timer = new Timer();
        timer.schedule(new TaskLogLevel(), 0, 1000);
    }//from   w w  w  .  j a  v a2 s  .c o  m

    LOG.debug("Launching C++ thru JNI");
    buildCmdParams();

    LOG.info("going to execute C++ thru JNI with argc=: " + mCmdParams.size() + " cmd: " + mCmdParams);
    String[] stringarray = mCmdParams.toArray(new String[0]);

    // if parameter is set to "true", UDA will log into its own files.
    Boolean log_to_uda_file = mjobConf.getBoolean("mapred.uda.log.to.unique.file", false);

    try {
        UdaBridge.start(isNetMerger, stringarray, LOG, log_level, log_to_uda_file, _callable);

    } catch (UnsatisfiedLinkError e) {
        LOG.warn("UDA: Exception when launching child");
        LOG.warn("java.library.path=" + System.getProperty("java.library.path"));
        LOG.warn(StringUtils.stringifyException(e));
        throw (e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.semantic.SimpleSemanticFactory.java

/**
 * Creates temporary files for ontology document storing and
 * sets the timer to run the transformation process regularly.
 */// w w  w  .  ja v a 2  s . c  o m
public void init() {
    try {
        ontologyFile = File.createTempFile("ontology_", ".rdf.tmp");
        ontologyFile.deleteOnExit();
    } catch (IOException e) {
        log.error("Could not create the temporary rdf/xml file to store the ontology!", e);
    }

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TransformTask(), delay, interval);
}