Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

Usage

From source file:com.fluidops.iwb.api.ProviderServiceImpl.java

Timer scheduleProviders() {
    TimerTask timerTask = new TimerTask() {
        Queue<AbstractFlexProvider> queue = new ArrayBlockingQueue<AbstractFlexProvider>(10000);

        @Override/* www  .j a  v  a  2  s . com*/
        public void run() {
            try {
                if (queue.isEmpty()) {
                    // add any work
                    for (AbstractFlexProvider s : getProviders()) {
                        if (s.pollInterval <= 0)
                            continue; // disabled 

                        if (s.running != null && s.running == true)
                            continue;

                        if (s instanceof ExternalProvider)
                            continue;

                        if (s instanceof LookupProvider)
                            continue;

                        if (s.lastUpdate == null)
                            queue.add(s);
                        else if (s.lastUpdate.getTime() + s.pollInterval < System.currentTimeMillis())
                            queue.add(s);
                    }
                }
                if (!queue.isEmpty()) {
                    AbstractFlexProvider provider = queue.poll();
                    runProvider(provider.providerID, null);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    };
    Timer timer = new Timer("IWB Provider Update");
    timer.schedule(timerTask, 1000, 1000);
    TimerRegistry.getInstance().registerProviderServiceTimer(timer);
    return timer;
}

From source file:com.timemachine.controller.ControllerActivity.java

/**
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 *//*w  ww .j av a 2 s .  com*/
private void setUpMap() {
    if (!isMapTimedUpdate) {
        // Send the new lat lng and zoom to the server when the view is changed
        GoogleMap.OnCameraChangeListener listener = new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition position) {
                if (socket != null) {
                    socket.emit("mapViewUpdate",
                            Double.toString(position.target.latitude) + " "
                                    + Double.toString(position.target.longitude) + " "
                                    + Float.toString(position.zoom - timeMachineAndGoogleMapZoomOffset));
                    // Limit the max zoom
                    if (position.zoom > maxZoom) {
                        mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                    }
                }
            }
        };
        mMap.setOnCameraChangeListener(listener);
    } else {
        // Setup a timer to update the map location
        Timer updateMapTimer = new Timer();
        updateMapTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mapUpdateHandler.post(new Runnable() {
                    public void run() {
                        if (socket != null && isMapTimedUpdate) {
                            CameraPosition position = mMap.getCameraPosition();
                            double currentLat = Math.round(position.target.latitude * roundTo) / roundTo;
                            double currentLng = Math.round(position.target.longitude * roundTo) / roundTo;
                            float currentZoom = Math.round(position.zoom * (float) roundTo) / (float) roundTo;
                            if (currentLat != lastLat || currentLng != lastLng || currentZoom != lastZoom) {
                                socket.emit("mapViewUpdate", Double.toString(currentLat) + " "
                                        + Double.toString(currentLng) + " "
                                        + Double.toString(currentZoom - timeMachineAndGoogleMapZoomOffset));
                            }
                            // Limit the max zoom
                            if (position.zoom > maxZoom) {
                                mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                            }
                            lastLat = currentLat;
                            lastLng = currentLng;
                            lastZoom = currentZoom;
                        }
                    }
                });
            }
        }, mapUpdateTime, mapUpdateTime);
    }
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setTiltGesturesEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(false);
}

From source file:com.kyakujin.android.autoeco.ui.MainActivity.java

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

    mActivity = this;

    mAbout = (ImageButton) findViewById(R.id.buttonAbout);
    mAbout.setOnClickListener(this);
    if (Build.VERSION.SDK_INT >= 13) {
        mAbout.setVisibility(View.VISIBLE);
    } else {//from  w  ww.  j a  va 2 s. c om
        mAbout.setVisibility(View.INVISIBLE);
    }

    mTimeData = TimeData.getInstance();
    mTimeData.setHour(0);
    mTimeData.setMinute(0);

    mBattery = (LinearLayout) findViewById(R.id.batteryRoot);
    mBattery.setOnClickListener(this);
    mAddSched = (Button) findViewById(R.id.btnAddSched);
    mAddSched.setOnClickListener(this);
    mManual = (LinearLayout) findViewById(R.id.manualRoot);
    mManual.setOnClickListener(this);

    mBatteryDisabled = (TextView) findViewById(R.id.textBatteryDisabledInFrame);
    mBatteryAccount = (TextView) findViewById(R.id.textSetThresholdInFrame);
    mCurrentBattery = (LinearLayout) findViewById(R.id.layoutCurrentBattery);
    mCurrentBatteryLevel = (TextView) findViewById(R.id.textCurrentLevelInFrame);
    mCurrentThreshold = (TextView) findViewById(R.id.textThresholdInFrame);

    mSchedListView = (ListView) findViewById(android.R.id.list);
    mSchedListView.setOnItemClickListener(this);

    mSchedListAdapter = new SchedListAdapter(this, R.layout.list_item_sched, null,
            new String[] { SchedTbl.HOUR_MINUTE_STRING, }, new int[] { R.id.textHourMinute, }, 0);

    mSchedListView.setAdapter(mSchedListAdapter);
    registerForContextMenu(mSchedListView);

    mIsForeground = true;
    Timer timer = new Timer(false);
    // ????????
    timer.schedule(new TimerTask() {

        public void run() {
            // ??????(Timer???UI?????)
            runOnUiThread(new Runnable() {
                public void run() {
                    if (mIsForeground) {
                        Logger.d(TAG, "timertask.");
                        SetCurrentBatteryTask task = new SetCurrentBatteryTask(mCurrentBatteryLevel);
                        task.execute();
                    }

                }
            });
        }
    }, 0, 3000);

    mLoaderManager = getSupportLoaderManager();
    mLoaderManager.restartLoader(SchedQuery.LOADER_ID, null, this);
    mLoaderManager.restartLoader(ManualQuery.LOADER_ID, null, this);
    mLoaderManager.restartLoader(BatteryQuery.LOADER_ID, null, this);

    addAD();
}

From source file:esg.node.connection.ESGConnectionManager.java

private void periodicallyRegisterToPeers() {
    log.trace("Launching connection manager's registration push timer...");
    long delay = Long.parseLong(props.getProperty("conn.mgr.initialDelay", "10"));

    final long period = Long.parseLong(props.getProperty("conn.mgr.period", "30"));
    final long slop_bounds = 15000; //represents 15000ms or 15 seconds of slop.... slop/period is the ratio of period misses
    final Random random = new Random(System.currentTimeMillis());

    log.trace("connection registration delay:  " + delay + " sec");
    log.trace("connection registration period: " + period + " sec");

    Timer timer = new Timer("Reg-Repush-Timer");

    //This will transition from active map to inactive map
    timer.schedule(new TimerTask() {
        public final void run() {
            log.debug("(Timer) Re-Pushing My Last Registry State (Event)");
            long elapsedTime = (System.currentTimeMillis()
                    - ESGConnectionManager.this.lastDispatchTime.longValue());
            long window = ((period * 1000) + (Math.abs(random.nextLong()) % slop_bounds)); //milliseconds

            log.trace("Re-push: elapsedTime=" + elapsedTime + "ms >? window=" + window + "ms");

            if (elapsedTime > window) {
                ESGConnectionManager.this.getESGEventQueue().enqueueEvent(new ESGCallableFutureEvent<Boolean>(
                        ESGConnectionManager.this, Boolean.valueOf(false), "Registration Re-push Event") {
                    public boolean call(DataNodeComponent contextComponent) {
                        log.trace("Registration Re-push \"Call\"'ed...");
                        boolean handled = false;
                        try {
                            //Note: since "Boolean" generic, setData needs to take a value of that type
                            //"handled" plays *two* roles. 1) It is the Data that is being retrieved and stored
                            //by whatever process is coded (in this case calling sendOutRegistryState()).
                            //2) It is also setting the return value for this "call" method being implemented
                            //that indicates if this call was successfully handled.  The former has its type
                            //dictated by the generic.  The latter is always a boolean.
                            setData(handled = ((ESGConnectionManager) contextComponent).sendOutRegistryState());
                        } finally {
                            log.info("Registration Re-push completed [" + handled + "]");
                        }//from w ww  .ja  va 2  s.co  m
                        return handled;
                    }
                });
            } else {
                log.debug("NOT performing re-push - last message sent approx " + (elapsedTime / 1000)
                        + "secs ago < " + (window / 1000) + "secs");
            }
        }
    }, delay * 1000, period * 1000);
}

From source file:it.unime.mobility4ckan.MainActivity.java

private void startTimer() {
    Timer sendTimer = new Timer();
    sendTimer.schedule(new TimerTask() {
        @Override//from   w w w.ja v  a2s.  co  m
        public void run() {
            sendTask(true);
        }
    }, 0, countdown);
}

From source file:it.unime.mobility4ckan.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    sharedPref = getSharedPreferences("sharedprefs", MODE_PRIVATE);
    locationText = (TextView) findViewById(R.id.txv_gps);
    countdownText = (TextView) findViewById(R.id.txv_countdown);
    datasetNameText = (TextView) findViewById(R.id.txv_dataset);
    listView = (ListView) findViewById(R.id.sensor_listview);
    countdown = SensorConfig.countDownTimer;
    apikey = sharedPref.getString("userAPIkey", "");
    sendNowBtn = (Button) findViewById(R.id.btn_invia);
    sendNowBtn.setOnClickListener(new View.OnClickListener() {
        @Override/*  w  w  w .  jav  a  2  s .co m*/
        public void onClick(View v) {
            sendTask(false);
        }
    });
    checkPermissionControl();

    sensorList = SensorConfig.sensorList;
    mySensor = new MySensor(this);
    for (int k = 0; k < sensorList.size(); k++) {
        mySensor.registerSensor(sensorList.get(k));
    }

    if (!isDeviceOnline()) {
        final AlertDialog mDialog = new AlertDialog.Builder(this).setMessage(getString(R.string.sei_offline))
                .setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).create();
        mDialog.show();
        return;
    }

    if (!isGPSEnable()) {
        final AlertDialog mDialog = new AlertDialog.Builder(this)
                .setMessage(getString(R.string.gps_disattivato)).setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).create();
        mDialog.show();
        return;
    }

    if (sharedPref.getString("datasetName", "").isEmpty()) {
        setDatasetName();
    } else {
        datasetNameText.setText(sharedPref.getString("datasetName", ""));
        datasetName = sharedPref.getString("datasetName", "");
        startTimer();
    }

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    createListView();
                }
            });
        }
    }, 0, 3000);

}

From source file:com.ece420.lab3.MainActivity.java

public void initializeStftBackgroundThread(int timeInMs) {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override/*from w  ww .  ja  va 2s  .c  o m*/
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        UpdateStftTask performStftUiUpdate = new UpdateStftTask();
                        performStftUiUpdate.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, timeInMs); // execute every 50 ms
}

From source file:cl.gisred.android.RepartoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LicenseResult licenseResult = ArcGISRuntime.setClientId(CLIENT_ID);
    LicenseLevel licenseLevel = ArcGISRuntime.License.getLicenseLevel();

    if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.BASIC) {
        //Toast.makeText(getApplicationContext(), "Licencia bsica vlida", Toast.LENGTH_SHORT).show();
    } else if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.STANDARD) {
        //Toast.makeText(getApplicationContext(), "Licencia standard vlida", Toast.LENGTH_SHORT).show();
    }/*  w w w  .  j  a v  a  2s  .  co  m*/

    setContentView(R.layout.activity_reparto);

    Toolbar toolbar = (Toolbar) findViewById(R.id.apptool);
    setSupportActionBar(toolbar);

    myMapView = (MapView) findViewById(R.id.map);
    myMapView.enableWrapAround(true);

    /*Get Credenciales String*/
    Bundle bundle = getIntent().getExtras();
    usuar = bundle.getString("usuario");
    passw = bundle.getString("password");
    modulo = bundle.getString("modulo");
    empresa = bundle.getString("empresa");

    //Crea un intervalo entre primer dia del mes y dia actual
    Calendar oCalendarStart = Calendar.getInstance();
    oCalendarStart.set(Calendar.DAY_OF_MONTH, 1);
    oCalendarStart.set(Calendar.HOUR, 6);

    Calendar oCalendarEnd = Calendar.getInstance();
    oCalendarEnd.set(Calendar.HOUR, 23);

    TimeExtent oTimeInterval = new TimeExtent(oCalendarStart, oCalendarEnd);

    //Set Credenciales
    setCredenciales(usuar, passw);

    if (Build.VERSION.SDK_INT >= 23)
        verifPermisos();
    else
        startGPS();

    setLayersURL(this.getResources().getString(R.string.url_Mapabase), "MAPABASE");
    setLayersURL(this.getResources().getString(R.string.url_token), "TOKENSRV");
    setLayersURL(this.getResources().getString(R.string.srv_Repartos), "SRV_REPARTO");

    LyMapabase = new ArcGISDynamicMapServiceLayer(din_urlMapaBase, null, credenciales);
    LyMapabase.setVisible(true);

    LyReparto = new ArcGISFeatureLayer(srv_reparto, ArcGISFeatureLayer.MODE.ONDEMAND, credenciales);
    LyReparto.setDefinitionExpression(String.format("empresa = '%s'", empresa));
    LyReparto.setTimeInterval(oTimeInterval);
    LyReparto.setMinScale(8000);
    LyReparto.setVisible(true);

    myMapView.addLayer(mRoadBaseMaps, 0);
    myMapView.addLayer(LyReparto, 1);

    sqlReparto = new RepartoSQLiteHelper(RepartoActivity.this, dbName, null, 2);

    txtContador = (TextView) findViewById(R.id.tvContador);
    txtContSesion = (TextView) findViewById(R.id.tvContadorSesion);

    txtListen = (EditText) findViewById(R.id.txtListen);
    txtListen.setEnabled(bGpsActive);
    if (!txtListen.hasFocus())
        txtListen.requestFocus();
    txtListen.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().contains("\n") || s.toString().length() == RepartoClass.length_code) {
                guardarRegistro(s.toString().trim());
                s.clear();
            }
        }
    });

    final FloatingActionButton btnGps = (FloatingActionButton) findViewById(R.id.action_gps);
    btnGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                myMapView.setExtent(ldm.getPoint());
                myMapView.setScale(4000, true);
            }
        }
    });

    myMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
        @Override
        public void onStatusChanged(Object o, STATUS status) {
            if (ldm != null) {
                Point oPoint = ldm.getPoint();
                myMapView.centerAndZoom(oPoint.getX(), oPoint.getY(), 0.003f);
                myMapView.zoomin(true);
            }

            if (status == STATUS.LAYER_LOADING_FAILED) {
                // Check if a layer is failed to be loaded due to security
                if ((status.getError()) instanceof EsriSecurityException) {
                    EsriSecurityException securityEx = (EsriSecurityException) status.getError();
                    if (securityEx.getCode() == EsriSecurityException.AUTHENTICATION_FAILED)
                        Toast.makeText(myMapView.getContext(),
                                "Su cuenta tiene permisos limitados, contacte con el administrador para solicitar permisos faltantes",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_INVALID)
                        Toast.makeText(myMapView.getContext(), "Token invlido! Vuelva a iniciar sesin!",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_SERVICE_NOT_FOUND)
                        Toast.makeText(myMapView.getContext(),
                                "Servicio token no encontrado! Reintente iniciar sesin!", Toast.LENGTH_SHORT)
                                .show();
                    else if (securityEx.getCode() == EsriSecurityException.UNTRUSTED_SERVER_CERTIFICATE)
                        Toast.makeText(myMapView.getContext(), "Untrusted Host! Resubmit!", Toast.LENGTH_SHORT)
                                .show();

                    if (o instanceof ArcGISFeatureLayer) {
                        // Set user credential through username and password
                        UserCredentials creds = new UserCredentials();
                        creds.setUserAccount(usuar, passw);

                        LyMapabase.reinitializeLayer(creds);
                    }
                }
            }
        }
    });

    readCountData();
    updDashboard();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (iContRep > 0) {
                        Toast.makeText(getApplicationContext(), "Sincronizando datos...", Toast.LENGTH_SHORT)
                                .show();
                        readData();
                        enviarDatos();
                    }
                }
            });

        }
    }, 0, 120000);
}