Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

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

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

    /*// ww  w.  j a  v a  2 s . com
     * 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:deincraftlauncher.start.StartMinecraft.java

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

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override/* w w w  .j ava 2  s.  c  o 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:me.Aron.Heinecke.fbot.fbot.java

/****
 * registers the timed task to download both pdfs
 *//*  www .  j  a  v  a 2s. co m*/
private static void registerThreads() {
    maintimer = new Timer(true);
    filetask = new TimerTask() {
        public void run() {
            hash1 = Task(0, hash1);
            hash2 = Task(1, hash2);
        }
    };
    maintimer.schedule(filetask, 0, 1000 * interval);// 1000*sec
}

From source file:com.sidekickApp.PusherClass.java

private void startInputTimer() {
    log("startInputTimer()");
    inputTimer = new Timer("inputTimer", true);
    long initialDelay = 0;
    long interval = 2000;

    inputTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            // calculate decay
            interest = interest + numEvents * 50;
            numEvents = 0;//from w w w.  ja va2s . c  o  m
        }
    }, initialDelay, interval);
}

From source file:org.camunda.bpm.extension.elasticsearch.cockpit.demodata.DemoDataGenerator.java

protected void scheduleInstanceStart() {
    new Timer(true).schedule(new TimerTask() {
        public void run() {

            // start some process instances
            int rand = new Random().nextInt(maxInstances);
            for (int i = 0; i < rand; i++) {
                processEngine.getRuntimeService().startProcessInstanceByKey("generatedFormsQuickstart");
            }//from  w  w w . j  a  v  a  2 s  .com

            // complete some process instances
            rand = new Random().nextInt(maxInstances);
            List<Task> tasks = processEngine.getTaskService().createTaskQuery().listPage(0, rand);
            for (Task task : tasks) {
                processEngine.getTaskService().complete(task.getId());
            }

            // reschedule
            scheduleInstanceStart();
        }
    }, 1000);
}

From source file:com.inbravo.scribe.rest.service.crm.cache.CRMSessionCache.java

public final void initialize() {
    if (cacheManager != null) {
        cacheManager.cancel();//from w ww.j av  a 2  s .  c  om
    }
    cacheManager = new Timer(true);
    cacheManager.schedule(new TimerTask() {
        public void run() {
            long now = System.currentTimeMillis();
            try {
                MapIterator itr = cacheMap.mapIterator();
                while (itr.hasNext()) {
                    Object key = itr.next();
                    final CachedObject cobj = (CachedObject) itr.getValue();
                    if (cobj == null || cobj.hasExpired(now)) {

                        if (logger.isDebugEnabled()) {
                            logger.debug("----Inside CRMSessionCache: removing " + key + ": Idle time= "
                                    + (now - cobj.timeAccessedLast) + "; Stale time= " + (now - cobj.timeCached)
                                    + "; Object count in cache= " + cacheMap.size());
                        }
                        itr.remove();
                        Thread.yield();
                    }
                }
            } catch (ConcurrentModificationException cme) {
                /*
                 * This is just a timer cleaning up. It will catch up on cleaning next time it runs.
                 */
                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside CRMSessionCache:Ignorable ConcurrentModificationException");
                }
            }
        }
    }, 0, tiv);
}

From source file:burstcoin.observer.service.AssetService.java

private void startCheckAssetsTask() {
    timer.schedule(new TimerTask() {
        @Override//from   w  w  w.j a va  2  s  . co  m
        public void run() {
            try {
                LOG.info("START import asset data from " + ObserverProperties.getWalletUrl());
                Map<String, Asset> assetLookup = createAssetLookup();
                Map<OrderType, Map<Asset, List<Order>>> orderLookup = createOrderLookup(assetLookup);
                Map<Asset, List<Trade>> tradeLookup = getTradeLookup(assetLookup);

                State state = getState();
                LOG.info("FINISH import asset data!");

                List<AssetBean> assetBeans = new ArrayList<>();
                List<AssetCandleStickBean> assetCandleStickBeans = new ArrayList<>();
                for (Asset asset : assetLookup.values()) {
                    List<List> candleStickData = new ArrayList<List>();
                    long volume7Days = 0L;
                    long volume30Days = 0L;
                    String lastPrice = "";
                    List<Trade> trades = tradeLookup.get(asset);
                    if (trades != null && !trades.isEmpty()) {
                        Iterator<Trade> iterator = trades.iterator();
                        boolean withinLast30Days = true;

                        while (withinLast30Days && iterator.hasNext()) {
                            Trade trade = iterator.next();
                            if (StringUtils.isEmpty(lastPrice)) {
                                lastPrice = convertPrice(trade.getPriceNQT(), trade.getDecimals());
                            }

                            Integer bidOrderBlock = Integer.valueOf(trade.getBidOrderHeight());
                            Integer askOrderBlock = Integer.valueOf(trade.getAskOrderHeight());
                            int block = bidOrderBlock >= askOrderBlock ? bidOrderBlock : askOrderBlock;
                            withinLast30Days = state.getNumberOfBlocks() - 360 * 30 < block;

                            if (withinLast30Days) {
                                long volume = Long.valueOf(trade.getPriceNQT())
                                        * Long.valueOf(trade.getQuantityQNT());
                                volume30Days += volume;

                                if (state.getNumberOfBlocks() - 360 * 7 < block) {
                                    volume7Days += volume;
                                }
                            }
                        }

                        Long currentBlockHeight = Long.valueOf(state.getNumberOfBlocks());

                        for (int i = 1; i <= 60 /*days*/; i++) {
                            List<Trade> tradesOfDay = new ArrayList<Trade>();
                            for (Trade trade : trades) {
                                if (trade.getHeight() > currentBlockHeight - (360 * (i + 1))
                                        && trade.getHeight() < currentBlockHeight - (360 * i)) {
                                    tradesOfDay.add(trade);
                                }
                            }

                            Double min = null;
                            Double max = null;
                            Double first = null;
                            Double last = null;

                            for (Trade trade : tradesOfDay) {
                                double price = Double
                                        .valueOf(convertPrice(trade.getPriceNQT(), trade.getDecimals()));
                                if (first == null) {
                                    first = price;
                                }
                                if (min == null || price < min) {
                                    min = price;
                                }
                                if (max == null || price > max) {
                                    max = price;
                                }
                                if (tradesOfDay.indexOf(trade) == tradesOfDay.size() - 1) {
                                    last = price;
                                }
                            }

                            if (min != null && max != null && first != null && last != null) {
                                List x = Arrays.asList("" + i, min, first, last, max);
                                candleStickData.add(x);
                            } else {
                                candleStickData.add(Arrays.asList("" + i, null, null, null, null));
                            }
                        }
                    }

                    Collections.reverse(candleStickData);

                    List<Order> sellOrders = orderLookup.get(OrderType.ASK).get(asset) != null
                            ? orderLookup.get(OrderType.ASK).get(asset)
                            : new ArrayList<>();
                    List<Order> buyOrders = orderLookup.get(OrderType.BID).get(asset) != null
                            ? orderLookup.get(OrderType.BID).get(asset)
                            : new ArrayList<>();

                    if (!(buyOrders.isEmpty() && sellOrders.isEmpty() && asset.getNumberOfTrades() < 2)) {
                        assetBeans.add(new AssetBean(asset.getAsset(), asset.getName(), asset.getDescription(),
                                asset.getAccountRS(), asset.getAccount(), asset.getQuantityQNT(),
                                asset.getDecimals(), asset.getNumberOfAccounts(), asset.getNumberOfTransfers(),
                                asset.getNumberOfTrades(), buyOrders.size(), sellOrders.size(),
                                formatAmountNQT(volume7Days, 8), formatAmountNQT(volume30Days, 8), lastPrice));
                        assetCandleStickBeans.add(new AssetCandleStickBean(asset.getAsset(), candleStickData));
                    }
                }
                Collections.sort(assetBeans, new Comparator<AssetBean>() {
                    @Override
                    public int compare(AssetBean o1, AssetBean o2) {
                        return Long.valueOf(o2.getVolume30Days()).compareTo(Long.valueOf(o1.getVolume30Days()));
                    }
                });
                Collections.sort(assetBeans, new Comparator<AssetBean>() {
                    @Override
                    public int compare(AssetBean o1, AssetBean o2) {
                        return Long.valueOf(o2.getVolume7Days()).compareTo(Long.valueOf(o1.getVolume7Days()));
                    }
                });

                // delete data of candleStick for all after index 24 todo remove as soon ui has show/hide charts per asset
                List<String> assetOrder = new ArrayList<String>();
                for (AssetBean assetBean : assetBeans) {
                    assetOrder.add(assetBean.getAsset());
                }
                assetCandleStickBeans.sort(new Comparator<AssetCandleStickBean>() {
                    @Override
                    public int compare(AssetCandleStickBean o1, AssetCandleStickBean o2) {
                        return ((Integer) assetOrder.indexOf(o1.getAsset()))
                                .compareTo(assetOrder.indexOf(o2.getAsset()));
                    }
                });

                publisher.publishEvent(new AssetUpdateEvent(assetBeans, assetCandleStickBeans));
            } catch (Exception e) {
                LOG.error("Failed update assets!", e);
            }
        }
    }, 200, ObserverProperties.getAssetRefreshInterval());
}

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

@Override
public void start() {
    stop();//from ww w  .  j a va2  s  . c om

    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:me.rkfg.xmpp.bot.plugins.FaggotOfTheDayPlugin.java

private void startTimer() {
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override// w  w w.j  a va  2s. co  m
        public void run() {
            log.info(" A new day starts in the Empire ?");

            calculateFaggot();
        }

    }, getFirstTime(), PERIOD);
}

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

@Test
/**/* w  w w . j av a2s. c o 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));
}