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:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

@PostConstruct
private void initialize() {
    this.httpClient = newClient();
    SOCKET_TIMEOUT.addCallback(this.clientloader);
    CONNECTION_TIMEOUT.addCallback(this.clientloader);
    this.connectionManagerTimer.schedule(new TimerTask() {
        @Override/*from  ww  w.j ava2 s.  co  m*/
        public void run() {
            if (SimpleHostRoutingFilter.this.connectionManager == null) {
                return;
            }
            SimpleHostRoutingFilter.this.connectionManager.closeExpiredConnections();
        }
    }, 30000, 5000);
}

From source file:org.fatal1t.forexapp.spring.api.adapters.APIStreamingAdapter.java

@Override
public void start() {
    this.session = AppSession.getSession();
    initate();/* w ww.  ja  v  a 2 s  .c o  m*/
    try {
        /// Tick data listenener 
        List<String> testSymbols = new ArrayList<>();
        List<String> symbols;
        testSymbols.add("EURUSD");
        testSymbols.add("EURGBP");
        testSymbols.add("EURCZK");
        symbols = loadSymbols();
        final StreamingListener tickListener = new StreamingListener() {
            @Override
            public void receiveTickRecord(STickRecord tickRecord) {
                TickRecord record = new TickRecord(tickRecord.getAsk(), tickRecord.getBid(),
                        tickRecord.getAskVolume(), tickRecord.getBidVolume(), tickRecord.getHigh(),
                        tickRecord.getLow(), tickRecord.getSpreadRaw(), tickRecord.getSpreadTable(),
                        tickRecord.getSymbol(), tickRecord.getQuoteId(), tickRecord.getLevel(),
                        tickRecord.getTimestamp());
                log.info("Async: prijata Tick zprava: " + record.getSymbol());
                connector.sendMessage(record);
            }

            @Override
            public void receiveCandleRecord(SCandleRecord candleRecord) {
                CandleDataRecord record = new CandleDataRecord(candleRecord.getCtm(),
                        candleRecord.getCtmString(), candleRecord.getOpen(), candleRecord.getHigh(),
                        candleRecord.getLow(), candleRecord.getClose(), candleRecord.getVol(),
                        candleRecord.getQuoteId(), candleRecord.getSymbol());
                log.info("Async: prijata Candles zprava: " + record.getSymbol());
                connector.sendMessage(record);
            }

            @Override
            public void receiveBalanceRecord(SBalanceRecord record) {
                BalanceRecord newRecord = new BalanceRecord(record);
                connector.sendMessage(newRecord);
            }

            @Override
            public void receiveNewsRecord(SNewsRecord record) {
                NewsRecord newRecord = new NewsRecord(record);
                connector.sendMessage(newRecord);
            }

            @Override
            public void receiveKeepAliveRecord(SKeepAliveRecord keepAliveRecord) {

            }

            @Override
            public void receiveTradeRecord(STradeRecord record) {
                TradeRecord newRecord = new TradeRecord(record);
                connector.sendMessage(newRecord);
            }
        };
        this.tickConnector.connectStream(tickListener);
        this.tickConnector.subscribePrices(symbols);
        this.tickConnector.subscribeCandles(symbols);
        this.tickConnector.subscribeBalance();
        this.tickConnector.subscribeKeepAlive();
        this.tickConnector.subscribeNews();
        this.tickConnector.subscribeTrades();

        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    tickConnector.safeExecuteCommand(APICommandFactory.createPingCommand());
                } catch (APICommandConstructionException | APICommunicationException ex) {
                    try {
                        log.error("Problem s konektort, restartuju");
                        tickConnector.close();
                        tickConnector = initConnector();
                        tickConnector.connectStream(tickListener);
                        tickConnector.subscribePrices(symbols);
                        tickConnector.subscribeCandles(symbols);
                        tickConnector.subscribeBalance();
                        tickConnector.subscribeKeepAlive();
                        tickConnector.subscribeNews();
                        tickConnector.subscribeTrades();
                    } catch (IOException | APICommunicationException ex1) {
                        log.fatal(ex1.getStackTrace());

                    }
                }

            }
        }, 300000, 300000);
    } catch (IOException | APICommunicationException ex) {
        ex.printStackTrace();
    }
}

From source file:com.jbrisbin.vcloud.cache.RabbitMQAsyncCacheProvider.java

@Override
public void start() {
    active.set(true);/*  w  w w .j  a v  a 2 s . com*/

    try {
        Channel channel = getConnection().createChannel();
        channel.exchangeDeclare(objectRequestExchange, "topic", true, false, null);
        channel.queueDeclare(cacheNodeQueueName, true, false, true, null);
        channel.queueBind(cacheNodeQueueName, objectRequestExchange, "#");
        channel.exchangeDeclare(heartbeatExchange, "fanout", true, false, null);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    activeTasks.add(workerPool.submit(new HeartbeatMonitor()));
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            commandMessages.add(new CommandMessage("ping", heartbeatExchange, ""));
        }
    }, 0, heartbeatInterval);
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            numOfPeers.set(peers.size());
            if (debug) {
                log.debug("Expecting responses from " + numOfPeers.get() + " peers.");
            }
        }
    }, heartbeatInterval, heartbeatInterval);

    for (int i = 0; i < maxWorkers; i++) {
        activeTasks.add(workerPool.submit(new ObjectSender()));
        activeTasks.add(workerPool.submit(new CommandSender()));
        workerPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Channel channel = getConnection().createChannel();
                    ObjectMonitor monitor = new ObjectMonitor(channel);
                    channel.basicConsume(cacheNodeQueueName, monitor);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}

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

public void sendSearch() {
    List<String> killKeys = new ArrayList<String>();

    long killPoint = new Date().getTime() - SSDP_TIMEOUT;

    for (String key : foundServices.keySet()) {
        ServiceDescription service = foundServices.get(key);
        if (service == null || service.getLastDetection() < killPoint) {
            killKeys.add(key);//  ww w  . j  a va 2s .co  m
        }
    }

    for (String key : killKeys) {
        final ServiceDescription service = foundServices.get(key);

        if (service != null) {
            Util.runOnUI(new Runnable() {

                @Override
                public void run() {
                    for (DiscoveryProviderListener listener : serviceListeners) {
                        listener.onServiceRemoved(SSDPDiscoveryProvider.this, service);
                    }
                }
            });
        }

        if (foundServices.containsKey(key))
            foundServices.remove(key);
    }

    for (JSONObject searchTarget : serviceFilters) {
        SSDPSearchMsg search = null;
        try {
            search = new SSDPSearchMsg(searchTarget.getString("filter"));
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        final String message = search.toString();

        Timer timer = new Timer();
        /* Send 3 times like WindowsMedia */
        for (int i = 0; i < 3; i++) {
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    try {
                        if (mSSDPSocket != null)
                            mSSDPSocket.send(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            timer.schedule(task, i * 1000);
        }
    }
    ;
}

From source file:dk.netarkivet.wayback.indexer.WaybackIndexer.java

/**
 * Starts the producer thread. This thread runs on a timer. It downloads a list of all files in the archive and adds
 * any new ones to the database. It then checks the database for unindexed files and adds them to the queue.
 *//*  www.jav  a2 s  . c om*/
private static void startProducerThread() {
    Long producerDelay = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_DELAY);
    Long producerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_INTERVAL);
    Long recentProducerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_RECENT_PRODUCER_INTERVAL);
    TimerTask completeProducerTask = new TimerTask() {
        @Override
        public void run() {
            log.info("Starting producer task for all filenames");
            IndexerQueue iq = IndexerQueue.getInstance();
            iq.populate();
            FileNameHarvester.harvestAllFilenames();
            iq.populate();
        }
    };
    Timer producerThreadTimer = new Timer("ProducerThread");
    producerThreadTimer.schedule(completeProducerTask, producerDelay, producerInterval);
    TimerTask recentProducerTask = new TimerTask() {
        @Override
        public void run() {
            log.info("Starting producer task for recent files");
            IndexerQueue iq = IndexerQueue.getInstance();
            iq.populate();
            FileNameHarvester.harvestRecentFilenames();
            iq.populate();
        }
    };
    producerThreadTimer.schedule(recentProducerTask, producerDelay, recentProducerInterval);
}

From source file:com.google.android.apps.mytracks.samples.api.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*w w w.  ja  v a2s . c  o m*/

    // for the MyTracks content provider
    myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
    outputTextView = (TextView) findViewById(R.id.output);
    latTV = (TextView) findViewById(R.id.lat);
    lonTV = (TextView) findViewById(R.id.lon);
    timeTV = (TextView) findViewById(R.id.time);
    accuracyTV = (TextView) findViewById(R.id.accuracy);
    altitudeTV = (TextView) findViewById(R.id.altitude);
    speedTV = (TextView) findViewById(R.id.speed);
    bearingTV = (TextView) findViewById(R.id.bearing);

    Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button);
    addWaypointsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Track> tracks = myTracksProviderUtils.getAllTracks();
            Calendar now = Calendar.getInstance();
            for (Track track : tracks) {
                Waypoint waypoint = new Waypoint();
                waypoint.setTrackId(track.getId());
                waypoint.setName(now.getTime().toLocaleString());
                waypoint.setDescription(now.getTime().toLocaleString());
                myTracksProviderUtils.insertWaypoint(waypoint);
            }
        }
    });

    // for the MyTracks service
    intent = new Intent();
    ComponentName componentName = new ComponentName(getString(R.string.mytracks_service_package),
            getString(R.string.mytracks_service_class));
    intent.setComponent(componentName);

    Button startRecordingButton = (Button) findViewById(R.id.start_recording_button);
    startRecordingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myTracksService != null) {
                try {
                    myTracksService.startNewTrack();
                } catch (RemoteException e) {
                    Log.e(TAG, "RemoteException", e);
                }
                // rborisov start posting every X seconds
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @SuppressWarnings("unused")
                    @Override
                    public void run() {
                        //                Track lastTrack;
                        Location loc;
                        //                lastTrack = myTracksProviderUtils.getLastTrack();
                        //                outputTextView.append(" -" + lastTrack.getId() + "- ");
                        loc = myTracksProviderUtils.getLastValidTrackPoint();//lastTrack.getId());
                        if (loc != null) {

                            // Create a new HttpClient and Post Header
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://track.rborisov.me/trackmspost.php");

                            try {
                                // Add your data
                                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                                nameValuePairs
                                        .add(new BasicNameValuePair("lat", String.valueOf(loc.getLatitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("lon", String.valueOf(loc.getLongitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("time", String.valueOf(loc.getTime())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("accuracy", String.valueOf(loc.getAccuracy())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("altitude", String.valueOf(loc.getAltitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("speed", String.valueOf(loc.getSpeed())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("bearing", String.valueOf(loc.getBearing())));
                                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                                // Execute HTTP Post Request
                                HttpResponse response = httpclient.execute(httppost);

                            } catch (ClientProtocolException e) {
                                Log.e(TAG, "ClientProtocolException", e);
                            } catch (IOException e) {
                                Log.e(TAG, "IOException", e);
                            }
                        }
                    }
                }, 0, 30 * 1000);
                // rborisov end
            }
        }
    });

    Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button);
    stopRecordingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myTracksService != null) {
                try {
                    myTracksService.endCurrentTrack();
                    timer.cancel();
                    timer.purge();
                } catch (RemoteException e) {
                    Log.e(TAG, "RemoteException", e);
                }
            }
        }
    });
}

From source file:com.uproot.trackme.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your
 * app and process location updates. The app also shows how to convert
 * lat/long coordinates to human-readable addresses.
 *//*from  w w  w  . j av a  2  s  .  c  o  m*/
@SuppressLint({ "NewApi", "HandlerLeak" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // clearDB();
    initDatabase();

    Button btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });

    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mUseFine = false;
    mUseBoth = true;
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);

    // The isPresent() helper method is only available on Gingerbread or
    // above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and
    // address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    setup();

    myTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            getLocs();
        }
    }, 0, setF * 1000);

}

From source file:Model.RaptorUCIEngine.java

/**
 * Connects to the engine. After this method is invoked the engine name,
 * engine author, and options will be populated in this object.
 * //w w w .j  av  a 2s .  co  m
 * @return true if connection was successful, false otherwise.
 */
public boolean connect() {
    if (isConnected()) {
        return true;
    }

    resetConnectionState();

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

        @Override
        public void run() {
            logger.error("The engine could not load before timeout of 15 sec!");
            disconnect();
        }

    }, CONNECTION_TIMEOUT);

    try {

        process = new ProcessBuilder(processPath).directory(new File(new File(processPath).getParent()))
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (process != null) {
                    logger.info("Destroying UCI Engine");
                    process.destroy();
                }
            }
        });

        in = new BufferedReader(new InputStreamReader(process.getInputStream()), 10000);
        out = new PrintWriter(process.getOutputStream());

        send("uci");

        String currentLine = null;
        while ((currentLine = readLine()) != null) {

            if (currentLine.startsWith("id")) {
                parseIdLine(currentLine);
            } else if (currentLine.startsWith("option ")) {
                parseOptionLine(currentLine);
            } else if (currentLine.startsWith("uciok")) {
                break;
            } else {

            }
        }

        sendAllNonDefaultOptions();
        isReady();

        timer.cancel();

        return true;
    } catch (Throwable t) {
        disconnect();
        return false;
    }
}

From source file:org.kurento.demo.Pipeline.java

private void addPlayerListeners() {
    this.playerEndpoint.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override//from www  . j a  va 2s. c  om
        public void onEvent(EndOfStreamEvent event) {
            log.warn("Received EOS from Player");
            if (Pipeline.this.timer != null) {
                try {
                    Pipeline.this.timer.cancel();
                } catch (Exception e) {
                    log.debug("Empty timer");
                }
            }
            setFeedUrl(Pipeline.this.feedUrl);
        }
    });

    this.playerEndpoint.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent event) {
            synchronized (this) {
                log.error("Error received from Media server" + event.getDescription() + " "
                        + event.getErrorCode() + " " + event.getType());
                if (Pipeline.this.playing) {
                    Pipeline.this.playing = false;
                    log.error("Timer added to create the player again");
                    Pipeline.this.timer = new Timer();

                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            setFeedUrl(Pipeline.this.feedUrl);
                        }
                    };
                    Pipeline.this.timer.schedule(task, RECONNECTION_TIME);
                }
            }
        }
    });
}