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.datatorrent.lib.bucket.AbstractTimeBasedBucketManager.java

@Override
public void startService(Listener<T> listener) {
    bucketSlidingTimer = new Timer();
    endOBucketsInMillis = expiryTime + (noOfBuckets * bucketSpanInMillis);
    logger.debug("bucket properties {}, {}", daysSpan, bucketSpanInMillis);
    logger.debug("bucket time params: start {}, expiry {}, end {}", startOfBucketsInMillis, expiryTime,
            endOBucketsInMillis);//from ww  w .j a va2s.  co  m

    bucketSlidingTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            long time;
            synchronized (lock) {
                time = (expiryTime += bucketSpanInMillis);
                endOBucketsInMillis += bucketSpanInMillis;
                if (recordStats) {
                    bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOBucketsInMillis);
                    bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryTime);
                }
            }
            try {
                ((BucketStore.ExpirableBucketStore<T>) bucketStore).deleteExpiredBuckets(time);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }, bucketSpanInMillis, bucketSpanInMillis);
    super.startService(listener);
}

From source file:deincraftlauncher.IO.download.FTPDownloader.java

@Override
public void start() {

    if (!prepared) {
        prepare();/*from   w ww . ja  va  2 s  . c  o m*/
    }

    if (preparing) {
        try {
            prepareThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (started) {
        return;
    }

    started = true;

    System.out.println("starting ftp download: " + fileName);

    finished = false;
    updateNum = 0;

    downloadThread = new Thread() {
        @Override
        public void run() {

            System.out.println("FTPDownload Thread started");

            File targetPath = new File(saveTo);
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }

            saveTo += fileName;

            System.out.println("Starting Download; Link=" + link + " saveTo=" + saveTo);

            //Actual download code
            try {
                OutputStream output = new FileOutputStream(saveTo);
                CountingOutputStream cos = new CountingOutputStream(output) {

                    boolean updateReady = true;

                    @Override
                    protected void beforeWrite(int n) {
                        super.beforeWrite(n);

                        if (!updateReady) {
                            return;
                        }

                        totalProgress = this.getCount() / totalSize;

                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                updateReady = true;
                            }
                        }, updateDelay);

                        updateReady = false;
                    }
                };
                update();

                FTPConnection.getClient().retrieveFile(ftpfile.getName(), cos);

                cos.close();
                output.close();
                onFinished.call(instance);
                onFinishedB.call(instance);
                finished = true;
                System.out.println("Download fertig");
                started = false;
                //download fertig
                downloadThread.interrupt();

            } catch (IOException ex) {
                System.err.println("error while downliading via ftp: " + ex);
            }

        }
    };

    downloadThread.start();
    started = false;

}

From source file:ezbake.frack.common.workers.ProvenanceBatchWorker.java

/**
 * Initializes the worker with configuration and actions needed prior to
 * processing.//from  w  ww  .j a  va2 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:com.necla.simba.server.gateway.Main.java

public void serve() {
    try {/*from  w  w w. j a  v a2 s.c  o  m*/

        stats = new StatsCollector();
        stats.start("gateway.out");
        boolean frontendCompression = Boolean
                .parseBoolean(properties.getProperty("frontend.compression", "true"));
        FrontendFrameEncoder.DOCOMPRESS = frontendCompression;

        String nodes = properties.getProperty("simbastores");
        List<String> nodeArr = Arrays.asList(nodes.split("\\s*,\\s*"));
        backend = new BackendConnector(stats);
        subscriptionManager = new SubscriptionManager(backend);
        SeqNumManager sequencer = new SeqNumManager();
        final NotificationManager nom = new NotificationManager(sequencer);
        cam = new ClientAuthenticationManager(subscriptionManager, nom, backend, sequencer);
        subscriptionManager.setClientAuthenticationManager(cam);

        // dump all notification info
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                // LOG.debug("Flushing print buffer...");
                nom.dump();
                subscriptionManager.dump();
            }
        }, 0, 30000);
        StatsDumper dumper = new StatsDumper();
        dumper.start();

        backend.connect(properties, nodeArr, subscriptionManager, cam);
        FrontendServer frontend = new FrontendServer(properties, backend, stats, subscriptionManager, cam);

        LOG.debug("Gateway start-up complete.");

    } catch (IOException e) {
        LOG.error("Could not start server " + e.getMessage());
        System.exit(1);
    } catch (URISyntaxException e) {
        LOG.error("Invalid host specification: " + e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        LOG.error("Could not start server " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.easibeacon.examples.shop.MainActivity.java

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

    _barSearchBeacons = (ProgressBar) findViewById(R.id.barSearchBeacons);
    _txtState = (TextView) findViewById(R.id.txtState);

    ibp = IBeaconProtocol.getInstance(this);
    ibp.setListener(this);

    TimerTask searchIbeaconTask = new TimerTask() {
        @Override//from  ww w  .j a  v  a  2 s.c om
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    scanBeacons();
                }
            });
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(searchIbeaconTask, 1000, 2000);

}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

@PostConstruct
private void postConstruct() {
    gson = new Gson();

    log.info("Loading saved invites");
    Collection<ThreePidInviteIO> ioList = storage.getInvites();
    ioList.forEach(io -> {//from  w w  w .ja v a  2s. co  m
        log.info("Processing invite {}", gson.toJson(io));
        ThreePidInvite invite = new ThreePidInvite(new MatrixID(io.getSender()), io.getMedium(),
                io.getAddress(), io.getRoomId(), io.getProperties());

        ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), "");
        invitations.put(reply.getId(), reply);
    });

    // FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver
    try {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        // FIXME do better...
        throw new RuntimeException(e);
    }

    log.info("Setting up invitation mapping refresh timer");
    refreshTimer = new Timer();
    refreshTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                lookupMappingsForInvites();
            } catch (Throwable t) {
                log.error("Error when running background mapping refresh", t);
            }
        }
    }, 5000L, TimeUnit.MILLISECONDS.convert(cfg.getResolution().getTimer(), TimeUnit.MINUTES));
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowChartJDialog.java

/** Creates new form InvestmentFlowChartJDialog */
public InvestmentFlowChartJDialog(java.awt.Frame parent, boolean modal,
        PortfolioManagementJPanel portfolioManagementJPanel) {
    super(parent, modal);
    initComponents();//from w ww. j a  v  a2 s  .c o  m

    // Initialize main data structures.
    this.portfolioManagementJPanel = portfolioManagementJPanel;

    initJComboBox();

    // We need a stock price monitor, to update all the stocks value.
    initRealTimeStockMonitor();

    final JFreeChart freeChart = createChart();
    org.yccheok.jstock.charting.Utils.applyChartTheme(freeChart);
    this.chartPanel = new ChartPanel(freeChart, true, true, true, true, true);

    // Make chartPanel able to receive key event.
    // So that we may use arrow left/right key to move around yellow
    // information boxes. We may also use up/down key to perform combo box
    // selection.
    this.chartPanel.setFocusable(true);
    this.chartPanel.requestFocus();

    this.layer = new org.jdesktop.jxlayer.JXLayer<ChartPanel>(this.chartPanel);
    this.investmentFlowLayerUI = new InvestmentFlowLayerUI<ChartPanel>(this);
    layer.setUI(this.investmentFlowLayerUI);

    getContentPane().add(layer, java.awt.BorderLayout.CENTER);

    loadDimension();

    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            // Timeout. Remove busy message box.
            finishLookUpPrice = true;
            investmentFlowLayerUI.setDirty(true);
        }
    }, 15000);

    // Handle zoom-in.
    addChangeListener(this.chartPanel);

    // Handle resize.
    this.addComponentListener(new java.awt.event.ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            // Sequence is important. We will use invest information box as master.
            // ROI information box will be adjusted accordingly.
            investmentFlowLayerUI.updateInvestPoint();
            investmentFlowLayerUI.updateROIPoint();
        }
    });
}

From source file:burstcoin.jminer.core.round.Round.java

/**
 * Post construct./*from   w  w  w  .  j ava2s.  c  om*/
 */
@PostConstruct
protected void postConstruct() {
    this.poolMining = CoreProperties.isPoolMining();
    this.devPool = CoreProperties.isDevPool();
    this.devPoolCommitsPerRound = CoreProperties.getDevPoolCommitsPerRound();

    timer = new Timer();
}

From source file:net.hardisonbrewing.signingserver.SigservAutorunApplication.java

private void bootloader() {

    networkReadyListener = new MyNetworkReadyListener();
    addRadioListener(networkReadyListener);
    WLANInfo.addListener(networkReadyListener);

    Timer timer = new Timer();
    networkRequiredTimerTask = new NetworkRequiredTimerTask();
    timer.schedule(networkRequiredTimerTask, Dates.SECOND * 15, Dates.SECOND * 15);
}

From source file:com.dsh105.nexus.command.module.github.GitHubKeyCommand.java

@Override
public boolean onCommand(final CommandPerformEvent event) {
    if (event.getArgs().length == 0) {
        event.respond("Please follow the following instructions:", true);
        event.respond(//from  w  w  w .j  ava 2 s  .  c  om
                "- Visit "
                        + URLShortener
                                .shortenGit(AUTHORISE
                                        .replace("{client_id}",
                                                Nexus.getInstance().getGitHubConfig()
                                                        .getGitHubOauthAppClientId())
                                        .replace("{scope}",
                                                Nexus.getInstance().getGitHubConfig().getGitHubOauthAppScope())
                                        .replace("{state}", Nexus.getInstance().getGitHubConfig()
                                                .getGitHubOauthAppState())),
                true);
        event.respond("- Allow Nexus access.", true);
        event.respond(
                "- Copy the URL you are redirected to (the code information in this is important, so don't change anything!).",
                true);
        event.respond("- Perform {0}, where <code> is the URL you copied above.", true,
                Nexus.getInstance().getConfig().getCommandPrefix() + this.info().command() + " <code>");
        if (!event.isInPrivateMessage()) {
            event.respondWithPing(
                    "Please check your private messages for instructions on how to configure your GitHub API key.");
        }
        return true;
    } else if (event.getArgs().length == 1) {
        // request confirmed - check if valid
        String codeUrl = event.getArgs()[0];
        try {
            HashMap<String, String> params = getParams(codeUrl);
            String code = params.get("code");
            String state = params.get("state");
            if (code != null && state != null
                    && state.equals(Nexus.getInstance().getGitHubConfig().getGitHubOauthAppState())) {
                HttpResponse<JsonNode> response = Unirest.get(ACCESS_TOKEN
                        .replace("{client_id}",
                                Nexus.getInstance().getGitHubConfig().getGitHubOauthAppClientId())
                        .replace("{client_secret}",
                                Nexus.getInstance().getGitHubConfig().getGitHubOauthAppClientSecret())
                        .replace("{code}", code)).header("accept", "application/json").asJson();

                try {
                    final String accessToken = response.getBody().getObject().getString("access_token");
                    final String nick = event.getSender().getNick();
                    Nexus.getInstance().sendIRC().message("NickServ", "info " + nick);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            String account = Nexus.getInstance().getNicksConfig().getAccountNameFor(nick);
                            if (account != null && !account.isEmpty()) {
                                Nexus.getInstance().getGitHubConfig().set("github-key-" + account, accessToken);
                                Nexus.getInstance().getGitHubConfig().save();
                                event.respondWithPing(
                                        "You may now use the Nexus commands requiring API key information (e.g. IRC notification settings).");
                            } else {
                                event.errorWithPing(
                                        "Oh no! Something bad happened. I couldn't retrieve your API key from GitHub :(");
                            }
                        }
                    }, 5000);
                    return true;
                } catch (JSONException e) {
                    event.errorWithPing("Access denied. Reason: \"{0}\"",
                            response.getBody().getObject().getString("error_description"));
                    return true;
                }
            } else {
                event.errorWithPing(
                        "This code isn't right! Please make sure you copy the entire URL into the command.");
                return true;
            }
        } catch (UnirestException e) {
            throw new GenericUrlConnectionException("Failed to connect.", e);
        } catch (MalformedURLException e) {
            event.errorWithPing(
                    "Invalid URL code provided. Please make sure you copy the entire URL into the command.");
            return true;
        }
    }
    return false;
}