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.stimulus.archiva.index.VolumeIndex.java

public void startup() {
    logger.debug("volumeindex is starting up");
    File lockFile = new File(volume.getIndexPath() + File.separatorChar + "write.lock");
    if (lockFile.exists()) {
        logger.warn(/* w  w w .  j a  v  a2 s . c  o  m*/
                "The server lock file already exists. Either another indexer is running or the server was not shutdown correctly.");
        logger.warn(
                "If it is the latter, the lock file must be manually deleted at " + lockFile.getAbsolutePath());
        logger.warn(
                "index lock file detected. the server was shutdown incorrectly. automatically deleting lock file.");
        logger.warn("indexer is configured to deal with only one indexer process.");
        logger.warn("if you are running more than one indexer, your index could be subject to corruption.");
        lockFile.delete();
    }
    scheduler = Executors.newScheduledThreadPool(1);
    scheduledTask = scheduler.scheduleWithFixedDelay(new TimerTask() {
        @Override
        public void run() {
            closeIndex();
        }
    }, indexOpenTime, indexOpenTime, TimeUnit.MILLISECONDS);
    Runtime.getRuntime().addShutdownHook(this);

}

From source file:net.freifunk.android.discover.Main.java

void updateMaps() {
    final String URL = "https://raw.githubusercontent.com/NiJen/AndroidFreifunkNord/master/MapUrls.json";

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    final ConnectivityManager connManager = (ConnectivityManager) getSystemService(
            this.getBaseContext().CONNECTIVITY_SERVICE);
    final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    MapMaster mapMaster = MapMaster.getInstance();
    final DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this.getApplicationContext());
    final RequestQueueHelper requestHelper = RequestQueueHelper.getInstance(this.getApplicationContext());

    final HashMap<String, NodeMap> mapList = databaseHelper.getAllNodeMaps();

    final boolean sync_wifi = sharedPrefs.getBoolean("sync_wifi", true);
    final int sync_frequency = Integer.parseInt(sharedPrefs.getString("sync_frequency", "0"));

    if (sync_wifi == true) {
        Log.d(TAG, "Performing online update ONLY via wifi, every " + sync_frequency + " minutes");
    } else {/*from   w  w w .  java  2  s  . c  om*/
        Log.d(TAG, "Performing online update ALWAYS, every " + sync_frequency + " minutes");
    }

    updateTask = new TimerTask() {
        @Override
        public void run() {
            /* load from database */
            for (NodeMap map : mapList.values()) {
                map.loadNodes();
            }

            /* load from web */
            if (connManager.getActiveNetworkInfo() != null
                    && (sync_wifi == false || mWifi.isConnected() == true)) {
                Log.d(TAG, "Performing online update. Next update at " + scheduledExecutionTime());
                requestHelper.add(new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            MapMaster mapMaster = MapMaster.getInstance();

                            Iterator mapkeys = jsonObject.keys();
                            while (mapkeys.hasNext()) {
                                String mapName = mapkeys.next().toString();
                                String mapUrl = jsonObject.getString(mapName);

                                NodeMap m = new NodeMap(mapName, mapUrl);
                                databaseHelper.addNodeMap(m);

                                // only update, if not already found in database
                                if (!mapList.containsKey(m.getMapName())) {
                                    m.loadNodes();
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        } finally {
                            requestHelper.RequestDone();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.toString());
                        requestHelper.RequestDone();
                    }
                }));
            } else {
                Log.d(TAG, "Online update is skipped. Next try at " + scheduledExecutionTime());
            }
        }
    };

    Timer timer = new Timer();

    if (sync_frequency > 0) {
        timer.schedule(updateTask, 0, (sync_frequency * 60 * 1000));
    } else {
        timer.schedule(updateTask, 0);
    }

}

From source file:com.bigdata.dastor.db.Table.java

private Table(String table) throws IOException {
    name = table;/*from   www.j a  v a 2  s  .  com*/
    waitForCommitLog = DatabaseDescriptor.getCommitLogSync() == DatabaseDescriptor.CommitLogSync.batch;
    tableMetadata = Table.TableMetadata.instance(table);
    for (String columnFamily : tableMetadata.getColumnFamilies()) {
        columnFamilyStores.put(columnFamily, ColumnFamilyStore.createColumnFamilyStore(table, columnFamily));
    }

    // check 10x as often as the lifetime, so we can exceed lifetime by 10% at most
    int checkMs = DatabaseDescriptor.getMemtableLifetimeMS() / 10;
    flushTimer.schedule(new TimerTask() {
        public void run() {
            for (ColumnFamilyStore cfs : columnFamilyStores.values()) {
                try {
                    cfs.forceFlushIfExpired();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }, checkMs, checkMs);
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

void boot() {
    isStartingUp = true;//from  ww  w.ja  v  a 2s.  c  om
    ThreadState threadState = new SubjectThreadState(adminSubject);
    try {
        threadState.bind();
        internalInit();
        instance = this;
    } finally {
        threadState.clear();
        isStartingUp = false;
    }

    new Timer("onAppReady").schedule(new TimerTask() {
        @Override
        public void run() {
            ThreadState threadState = new SubjectThreadState(adminSubject);
            try {
                LoggerUtils.initDC();
                threadState.bind();
                onAppReady();
            } catch (InterruptedException ex) {
                // Do nothing...
            } finally {
                threadState.clear();
            }
        }
    }, 5000);
}

From source file:com.willwinder.ugs.nbp.setupwizard.panels.WizardPanelStepCalibration.java

@Override
public void initialize() {
    getBackend().addUGSEventListener(this);
    getBackend().addControllerStateListener(this);
    WizardUtils.killAlarm(getBackend());
    updateMeasurementEstimatesFields();//w  ww .j  av  a  2s.co m
    updateSettingFieldsFromFirmware();

    if (updateTimer != null) {
        updateTimer.cancel();
    }

    updateTimer = new Timer();
    updateTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Position currentPosition = getBackend().getWorkPosition();
            if (currentPosition != null) {
                labelPositionX.setText(
                        StringUtils.leftPad(decimalFormat.format(currentPosition.get(Axis.X)) + " mm", 8, ' '));
                labelPositionY.setText(
                        StringUtils.leftPad(decimalFormat.format(currentPosition.get(Axis.Y)) + " mm", 8, ' '));
                labelPositionZ.setText(
                        StringUtils.leftPad(decimalFormat.format(currentPosition.get(Axis.Z)) + " mm", 8, ' '));
                updateMeasurementEstimatesFields();
            }
            WizardUtils.killAlarm(getBackend());
        }
    }, 0, 200);
}

From source file:com.usertaxi.TaxiOntheWay_Activity.java

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

    taxiOntheWay_activity_instance = this;
    AppPreferences.setApprequestTaxiScreen(TaxiOntheWay_Activity.this, true);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);//w w  w  .  ja v a 2s  .c  o m
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);
    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    FloatingActionButton fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    FloatingActionButton fab_call = (FloatingActionButton) findViewById(R.id.fab_call);
    FloatingActionButton fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textheader = (TextView) findViewById(R.id.textheader);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    textheader.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);

    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    Log.d("data value", data + "");

    //caceldialog();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(data);
        AppPreferences.setAcceptdriverId(TaxiOntheWay_Activity.this, jsonObject.getString("driverId"));
        Log.d("driverid---", AppPreferences.getAcceptdriverId(TaxiOntheWay_Activity.this));
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        //driverlatitude = jsonObject.getDouble("latitude");
        //driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        //            Log.d("longitudeeeee:------", String.valueOf(jsonObject.getDouble("longitude")));

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        final MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        //  marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        //taxiname.setText(drivertaxiname);

        Intent intent1 = new Intent(TaxiOntheWay_Activity.this, DriverService.class);
        intent1.putExtra("driverId", jsonObject.getString("driverId"));
        startService(intent1);

        if (driverimage.equalsIgnoreCase("")) {
            mdriverimage.setImageResource(R.drawable.ic_action_user);
        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);
        }

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                        /* try{
                             String url = Function.getDirectionsUrl(new LatLng(Double.parseDouble(AppPreferences.getPreviouslat(getApplicationContext())),
                                     Double.parseDouble(AppPreferences.getPreviouslong(getApplicationContext()))),
                                     new LatLng(Double.parseDouble(AppPreferences.getCurrentlat(getApplicationContext())),
                                             Double.parseDouble(AppPreferences.getCurrentlong(getApplicationContext()))));
                             RoutesDownloadTask downloadTask = new RoutesDownloadTask(TaxiOntheWay_Activity.this);
                             downloadTask.execute(url);
                         }catch(Exception e)
                         {
                             e.printStackTrace();
                         }*/
                    }
                });
            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    /////////////notification dataend///////////////

    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });
    fab_call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + drivermobile));
            startActivity(callIntent);
        }
    });

    moveMarkerList = new ArrayList<LatLng>();
    //        moveRoadMarker();
}

From source file:bamboo.trove.full.FullReindexWarcManager.java

private void setTick() {
    if (timer == null) {
        timer = new Timer();
    }//from   w w w  .jav  a  2  s.  com
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            tick();
        }
    }, POLL_INTERVAL_SECONDS * 1000);
}

From source file:com.csipsimple.service.DownloadLibService.java

private void dumpFile(HttpEntity entity, File partialDestinationFile, File destinationFile) throws IOException {
    if (!cancellingDownload) {
        totalSize = (int) entity.getContentLength();
        if (totalSize <= 0) {
            totalSize = 1024;/*w  ww  .  ja va 2 s. c  om*/
        }

        byte[] buff = new byte[64 * 1024];
        int read = 0;
        RandomAccessFile out = new RandomAccessFile(partialDestinationFile, "rw");
        out.seek(0);
        InputStream is = entity.getContent();
        TimerTask progressUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                onProgressUpdate();
            }
        };
        Timer progressUpdateTimer = new Timer();
        try {
            // If File exists, set the Progress to it. Otherwise it will be
            // initial 0
            downloadedSize = 0;
            progressUpdateTimer.scheduleAtFixedRate(progressUpdateTimerTask, 100, 100);
            while ((read = is.read(buff)) > 0 && !cancellingDownload) {
                out.write(buff, 0, read);
                downloadedSize += read;
            }
            out.close();
            is.close();
            if (!cancellingDownload) {
                partialDestinationFile.renameTo(destinationFile);
            }
        } catch (IOException e) {
            out.close();
            try {
                destinationFile.delete();
            } catch (SecurityException ex) {
                Log.e(THIS_FILE, "Unable to delete downloaded File. Continue anyway.", ex);
            }
        } finally {
            progressUpdateTimer.cancel();
            buff = null;
        }
    }
}

From source file:com.zetcheck.SlidingStationActivity.java

License:asdf

@Override
public void onPause() {

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

        @Override//from   ww w  .  j av  a 2 s  . c  o  m
        public void run() {
            finish();
        }
    }, 1000 * 15);

    // Log.e("onpause", "a");
    super.onPause();
    if (adView != null) {
        adView.pause();
    }
    // isPaused=true;
}

From source file:com.sveder.cardboardpassthrough.MainActivity.java

private void callMessageTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override//from   w  w w .  j a v  a  2  s .  c  o m
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        MessageTask getMessageTask = new MessageTask(MainActivity.this);
                        getMessageTask.setMessageLoading(null);
                        getMessageTask.execute(TASKS_URL);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms

}