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:org.archive.crawler.framework.CheckpointService.java

/**
 * Setup checkpointTask according to current interval. (An already-scheduled
 * task, if any, is canceled.)/*from  w  w w. jav  a  2s . c  o  m*/
 */
protected synchronized void setupCheckpointTask() {
    if (checkpointTask != null) {
        checkpointTask.cancel();
    }
    if (!isRunning) {
        // don't setup before start (or after finish), even if
        // triggered by interval change
        return;
    }
    // Convert period from minutes to milliseconds.
    long periodMs = getCheckpointIntervalMinutes() * (60L * 1000L);
    if (periodMs <= 0) {
        return;
    }
    checkpointTask = new TimerTask() {
        public void run() {
            if (isCheckpointing()) {
                LOGGER.info("CheckpointTimerThread skipping checkpoint, " + "already checkpointing: State: "
                        + controller.getState());
                return;
            }
            LOGGER.info("TimerThread request checkpoint");
            requestCrawlCheckpoint();
        }
    };
    this.timer.schedule(checkpointTask, periodMs, periodMs);
    LOGGER.info("Installed Checkpoint TimerTask to checkpoint every " + periodMs + " milliseconds.");
}

From source file:com.frand.easyandroid.http.FFFileRespHandler.java

private void startTimer(final int reqTag, final String reqUrl) {
    timerInterrupt = false;//from  w  ww. j  a  va2 s. c  o  m
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            while (!timerInterrupt) {
                sendProgressMsg(totalSize, getDownloadSize(), networkSpeed, reqTag, reqUrl);
                try {
                    Thread.sleep(TIMERSLEEPTIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }, 0, 1000);
    new Thread(new Runnable() {

        @Override
        public void run() {

        }
    }).start();
}

From source file:multiplayer.pong.client.LobbyFrame.java

private void handleSockets() {
    socket.on("userConnected", new Emitter.Listener() {
        @Override/*from   w  w  w .j  av  a 2  s.  c  om*/
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            getConnectedFriends();
            if (connectedFriends.contains(username))
                appendMessage("Votre ami " + username + " vient de se connecter!\n", null);
            refresh();
        }
    }).on("connectedPlayers", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONArray players = (JSONArray) arg0[0];
            Vector<String> online = new Vector<String>();
            try {
                for (int i = 0; i < players.length(); i++) {
                    online.add(players.getJSONObject(i).getString("username"));
                }
            } catch (JSONException e) {
            }
            connectedPlayers = online;
            getConnectedFriends();
            refresh();
        }
    }).on("getMessage", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                appendMessage(data.getString("from") + ": " + data.getString("message") + "\n", null);
            } catch (JSONException e) {
            }
        }
    }).on("friendRequest", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String from = (String) arg0[0];
            displayNotification("Vouz avez une demande d'ajout de " + from + "\n");
            displayHelp("  >> Utilisez la commande '/accepterAmi " + from + "' pour confirmer la demande.\n");
        }
    }).on("friendRequestAck", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            displayNotification(username + " est maintenant votre ami.\n");
            displayHelp("Invitez le  une partie en tapant: '/challenge " + username + "'\n");
        }
    }).on("challenge", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            displayWarning(username + " vous invite  une partie de Pong\n");
            displayHelp("Tapez '/accepter " + username + "' pour joueur contre lui\n" + "ou '/refuser "
                    + username + "' pour refuser\n");
        }
    }).on("challengeAck", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                String opponent = data.getString("opponent");
                if (!data.getBoolean("accepted")) {
                    displayWarning(opponent + " a refus votre dfi.\n");
                } else {
                    // Start the game
                    daoGames.startGame(SocketHandler.username, opponent);
                    SocketHandler.startGame(opponent);
                }
            } catch (JSONException e) {
            }
        }
    }).on("startGame", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                String player1 = data.getString("player1");
                String player2 = data.getString("player2");
                if (SocketHandler.username.equals(player1) || SocketHandler.username.equals(player2)) {
                    socket.emit("joinRoom", player1);
                    displayWarning("La partie va commencer dans 5 secondes...\n");
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        String opponent = SocketHandler.username.equals(player1) ? player2 : player1;
                        String location = SocketHandler.username.equals(player1) ? "home" : "away";

                        public void run() {
                            Pong game = new Pong(location, opponent);
                        }
                    }, 5000);
                } else {
                    displayNotification("Un dfi a commenc: " + player1 + " vs " + player2 + "\n");
                }
            } catch (JSONException e) {
            }
        }
    }).on("userDisconnected", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            daoGames.cancelRequest(username, null);
            if (connectedFriends.contains(username))
                appendMessage("Votre ami " + username + " vient de se dconnecter!\n", null);
            connectedPlayers.remove(username);
            getConnectedFriends();
            refresh();
        }
    });
}

From source file:com.attentec.AttentecService.java

/**
 * Start recurring fetches of contacts and locations,
 * and also update our own location at intervals.
 *//*from w w w  . j ava2 s  . c  o m*/
private void startService() {
    Log.d(TAG, "startService");
    //fetch the interval for getting contacts
    contactsUpdateInterval = PreferencesHelper.getContactsUpdateInterval(this);

    //set the time updated to server to a long time ago
    lastUpdatedToServer = new Date().getTime()
            - DevelopmentSettings.MILLISECONDS_IN_MINUTE * DevelopmentSettings.MINUTES_IN_DAY;

    //Display a notification about us starting.  We put an icon in the status bar.
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();

    //initialize database contact
    dbh = new DatabaseAdapter(this);
    dbh.open();
    //get contacts every contactsUpdateInterval
    contactsTimer = new Timer();
    contactsTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            getContacts();
        }
    }, 0, contactsUpdateInterval);

    locationTimer = new Timer();
    locationTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            //get others locations
            getLocations();
        }
    }, 0, PreferencesHelper.getLocationsUpdateInterval(ctx));

    ownLocationTimer = new Timer();
    ownLocationTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (PreferencesHelper.getLocationUpdateEnabled(ctx)) {
                //get own location
                locationHelper.getLocation(ctx, locationResult);
                //check if we need to update the notification
            }
            updateNotificationIfNeeded();
        }
    }, 0, PreferencesHelper.getLocationsUpdateOwnInterval(ctx));

    isAlive = true;
    Intent serviceStartedIntent = new Intent(COM_ATTENTEC_SERVICE_CHANGED_STATUS);
    sendBroadcast(serviceStartedIntent);
}

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Execute the given request./*  w ww  .j  a v  a  2  s.c o m*/
 * <p>
 * Abort the request if it exceeds the specified timeout.
 *
 * @param httpClient The client to use.
 * @param request The request to make.
 * @param context The context to use.
 * @param timeout The timeout to use.
 * @return A Http Response.
 * @throws RestException Thrown if the request fails or times out.
 */
private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request,
        HttpClientContext context, int timeout) throws RestException {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            request.abort();
        }
    }, timeout);

    RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setConfig(localConfig);
    try {
        return httpClient.execute(request, context);
    } catch (IOException ex) {
        String requestUri = request.getURI().toString();
        if (request.isAborted()) {
            throw new RestException("Rest end point did not respond", requestUri);
        }
        throw new RestException("Rest call failed", requestUri, ex);
    }
}

From source file:flens.input.SpecInput.java

@Override
protected TimerTask getWorker() {
    return new TimerTask() {

        @Override/*w  ww . j  a va 2 s .  c  o m*/
        public void run() {
            for (Spec spec : specs) {
                try {
                    spec.run();
                } catch (Exception e) {
                    err("spec test failed ", e);
                }
            }

        }
    };
}

From source file:com.mobicage.rogerthat.registration.YSAAARegistrationActivity.java

private void register() {
    mStatusLbl.setText(R.string.initializing);
    mProgressBar.setProgress(0);/*from   w w  w  . ja  va 2  s . c  o  m*/
    mProgressBar.setVisibility(View.VISIBLE);

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            mUIHandler.post(new SafeRunnable() {
                @Override
                protected void safeRun() throws Exception {
                    T.UI();
                    mProgressBar.setProgress(mProgressBar.getProgress() + 1);
                }
            });
        }
    };
    mTimer.scheduleAtFixedRate(timerTask, 250, 250);

    mRetryBtn.setVisibility(View.GONE);
    if (!mService.getNetworkConnectivityManager().isConnected()) {
        mTimer.cancel();
        mProgressBar.setVisibility(View.GONE);
        mStatusLbl.setText(R.string.registration_screen_instructions_check_network_not_available);
        mRetryBtn.setVisibility(View.VISIBLE);
        UIUtils.showNoNetworkDialog(this);
        return;
    }

    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.UI();
            AlertDialog.Builder builder = new AlertDialog.Builder(YSAAARegistrationActivity.this);
            builder.setMessage(R.string.error_please_try_again);
            builder.setPositiveButton(R.string.rogerthat, null);
            AlertDialog dialog = builder.create();
            dialog.show();

            mTimer.cancel();
            mProgressBar.setVisibility(View.GONE);
            mStatusLbl.setText(R.string.error_please_try_again);
            mRetryBtn.setVisibility(View.VISIBLE);
        }
    };

    final String timestamp = "" + mWiz.getTimestamp();
    final String deviceId = mWiz.getDeviceId();
    final String registrationId = mWiz.getRegistrationId();
    final String installId = mWiz.getInstallationId();

    mWorkerHandler.post(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "1";
            String signature = Security.sha256(
                    version + " " + installId + " " + timestamp + " " + deviceId + " " + registrationId + " "
                            + CloudConstants.APP_SERVICE_GUID + CloudConstants.REGISTRATION_MAIN_SIGNATURE);

            HttpPost httppost = new HttpPost(CloudConstants.REGISTRATION_YSAAA_URL);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(13);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("platform", "android"));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("signature", signature));
                nameValuePairs.add(new BasicNameValuePair("install_id", installId));
                nameValuePairs.add(new BasicNameValuePair("service", CloudConstants.APP_SERVICE_GUID));
                nameValuePairs.add(new BasicNameValuePair("language", Locale.getDefault().getLanguage()));
                nameValuePairs.add(new BasicNameValuePair("country", Locale.getDefault().getCountry()));
                nameValuePairs.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));
                nameValuePairs.add(
                        new BasicNameValuePair("use_xmpp_kick", CloudConstants.USE_XMPP_KICK_CHANNEL + ""));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", mGCMRegistrationId));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    mUIHandler.post(showErrorDialog);
                    return;
                }

                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
                        .parse(new InputStreamReader(entity.getContent()));

                if (statusCode != 200 || responseMap == null) {
                    if (statusCode == 500 && responseMap != null) {
                        final String errorMessage = (String) responseMap.get("error");
                        if (errorMessage != null) {
                            mUIHandler.post(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    T.UI();
                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                            YSAAARegistrationActivity.this);
                                    builder.setMessage(errorMessage);
                                    builder.setPositiveButton(R.string.rogerthat, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();

                                    mTimer.cancel();
                                    mProgressBar.setVisibility(View.GONE);
                                    mStatusLbl.setText(errorMessage);
                                    mRetryBtn.setVisibility(View.VISIBLE);
                                }
                            });
                            return;
                        }
                    }
                    mUIHandler.post(showErrorDialog);
                    return;
                }
                JSONObject account = (JSONObject) responseMap.get("account");
                final String email = (String) responseMap.get("email");
                final RegistrationInfo info = new RegistrationInfo(email,
                        new Credentials((String) account.get("account"), (String) account.get("password")));
                mUIHandler.post(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWiz.setEmail(email);
                        mWiz.save();
                        tryConnect(1, getString(R.string.registration_establish_connection, email,
                                getString(R.string.app_name)) + " ", info);
                    }
                });

            } catch (Exception e) {
                L.d(e);
                mUIHandler.post(showErrorDialog);
            }
        }
    });
}

From source file:com.betfair.tornjak.monitor.DefaultMonitor.java

private void scheduleWarnExpiry() {
    cancelExistingWarnExpiry();//from  w w  w  .  j av  a2 s .  c om
    if (logger.isDebugEnabled()) {
        logger.debug(getName() + ": Scheduling warn expiry task to run in " + warningThreshold + "ms");
    }
    warnExpiry = new TimerTask() {
        @Override
        public void run() {
            StatusChangeEvent evt;
            synchronized (monitorLock) {
                if (logger.isDebugEnabled()) {
                    logger.debug(getName() + ": Executing warn expiry task");
                }
                evt = updateStatus();
            }
            if (evt != null) {
                fireStatusChangedEvent(evt);
            }
        }
    };
    timer.schedule(warnExpiry, warningThreshold);
}

From source file:com.librelio.activity.StartupActivity.java

protected void onStartMagazine(int delay) {
    mStartupAdsTimer = new Timer();
    mStartupAdsTimer.schedule(new TimerTask() {
        @Override/* w ww .j a  va  2  s. c o m*/
        public void run() {
            if (!advertisingClickPerformed) {
                startMainMagazineActivity();
            }
        }
    }, delay);
}

From source file:bamboo.trove.common.WarcProgressManager.java

private void setTick() {
    if (timer == null) {
        timer = new Timer();
    }/*from   w w  w .j a  v a  2 s  . co  m*/
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            checkQueues();
        }
    }, POLL_INTERVAL_SECONDS * 1000);
}