Example usage for java.util Timer scheduleAtFixedRate

List of usage examples for java.util Timer scheduleAtFixedRate

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.sintef.thingml.ThingMLPanel.java

public ThingMLPanel(Boolean ArduinoPlugin, final ObservableString transferBuf) {
    try {/* w  w  w  .  jav a2 s  .com*/
        this.setLayout(new BorderLayout());
        jsyntaxpane.DefaultSyntaxKit.initKit();
        jsyntaxpane.DefaultSyntaxKit.registerContentType("text/thingml",
                Class.forName("org.sintef.thingml.ThingMLJSyntaxKit").getName());
        JScrollPane scrPane = new JScrollPane(codeEditor);
        codeEditor.setContentType("text/thingml; charset=UTF-8");

        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
        reg.getExtensionToFactoryMap().put("thingml", new ThingmlResourceFactory());

        //codeEditor.setBackground(Color.LIGHT_GRAY)

        JMenuBar menubar = new JMenuBar();
        JInternalFrame menuframe = new JInternalFrame();

        menuframe.setSize(getWidth(), getHeight());
        menuframe.setJMenuBar(menubar);

        menuframe.setLayout(new BorderLayout());
        menuframe.add(scrPane, BorderLayout.CENTER);

        if (!ArduinoPlugin) {
            try {
                this.transferBuf = transferBuf;
                EditorKit editorKit = codeEditor.getEditorKit();
                JToolBar toolPane = new JToolBar();
                ((ThingMLJSyntaxKit) editorKit).addToolBarActions(codeEditor, toolPane);
                menuframe.add(toolPane, BorderLayout.NORTH);
            } catch (Exception e) {
                if (ThingMLApp.debug)
                    e.printStackTrace();
            }
        }

        menuframe.setVisible(true);
        ((BasicInternalFrameUI) menuframe.getUI()).setNorthPane(null);
        menuframe.setBorder(BorderFactory.createEmptyBorder());
        add(menuframe, BorderLayout.CENTER);

        if (!ArduinoPlugin) {//FIXME: Nicolas, avoid code duplication
            final ThingMLCompilerRegistry registry = ThingMLCompilerRegistry.getInstance();

            JMenu newCompilersMenu = new JMenu("Compile to");
            for (final String id : registry.getCompilerIds()) {
                JMenuItem item = new JMenuItem(id);
                ThingMLCompiler c = registry.createCompilerInstanceByName(id);
                if (c.getConnectorCompilers().size() > 0) {
                    JMenu compilerMenu = new JMenu(c.getID());
                    newCompilersMenu.add(compilerMenu);
                    compilerMenu.add(item);
                    for (final Map.Entry<String, CfgExternalConnectorCompiler> connectorCompiler : c
                            .getConnectorCompilers().entrySet()) {
                        JMenuItem connectorMenu = new JMenuItem(connectorCompiler.getKey());
                        compilerMenu.add(connectorMenu);
                        connectorMenu.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                ThingMLModel thingmlModel = ThingMLCompiler.loadModel(targetFile);
                                for (Configuration cfg : ThingMLHelpers.allConfigurations(thingmlModel)) {
                                    final ThingMLCompiler compiler = registry.createCompilerInstanceByName(id);
                                    for (NetworkPlugin np : loadedPlugins) {
                                        if (np.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addNetworkPlugin(np);
                                        }
                                    }
                                    for (SerializationPlugin sp : loadedSerPlugins) {
                                        if (sp.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addSerializationPlugin(sp);
                                        }
                                    }
                                    compiler.setOutputDirectory(new File(System.getProperty("java.io.tmpdir")
                                            + "/ThingML_temp/" + cfg.getName()));
                                    compiler.compileConnector(connectorCompiler.getKey(), cfg);
                                }
                            }
                        });
                    }
                } else {
                    newCompilersMenu.add(item);
                }

                item.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Input file : " + targetFile);
                        if (targetFile == null)
                            return;
                        try {
                            ThingMLModel thingmlModel = ThingMLCompiler.loadModel(targetFile);
                            if (thingmlModel != null) {
                                for (Configuration cfg : ThingMLHelpers.allConfigurations(thingmlModel)) {
                                    final ThingMLCompiler compiler = registry.createCompilerInstanceByName(id);
                                    for (NetworkPlugin np : loadedPlugins) {
                                        if (np.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addNetworkPlugin(np);
                                        }
                                    }
                                    for (SerializationPlugin sp : loadedSerPlugins) {
                                        if (sp.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addSerializationPlugin(sp);
                                        }
                                    }
                                    compiler.setOutputDirectory(new File(System.getProperty("java.io.tmpdir")
                                            + "/ThingML_temp/" + cfg.getName()));
                                    compiler.compile(cfg);
                                }
                            }
                        } catch (Exception ex) {
                            if (ThingMLApp.debug)
                                ex.printStackTrace();
                        }
                    }
                });
                c = null;
            }

            menubar.add(newCompilersMenu);
        } else {

            final ThingMLCompilerRegistry registry = ThingMLCompilerRegistry.getInstance();

            JMenu newCompilersMenu = new JMenu("Compile to");
            for (final String id : registry.getCompilerIds()) {
                if (id.compareToIgnoreCase("arduino") == 0) {
                    JMenuItem item = new JMenuItem(id);
                    ThingMLCompiler c = registry.createCompilerInstanceByName(id);
                    if (c.getConnectorCompilers().size() > 0) {
                        JMenu compilerMenu = new JMenu(c.getID());
                        newCompilersMenu.add(compilerMenu);
                        compilerMenu.add(item);
                        for (final Map.Entry<String, CfgExternalConnectorCompiler> connectorCompiler : c
                                .getConnectorCompilers().entrySet()) {
                            JMenuItem connectorMenu = new JMenuItem(connectorCompiler.getKey());
                            compilerMenu.add(connectorMenu);
                            connectorMenu.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    ThingMLModel thingmlModel = ThingMLCompiler.loadModel(targetFile);
                                    for (Configuration cfg : ThingMLHelpers.allConfigurations(thingmlModel)) {
                                        final ThingMLCompiler compiler = registry
                                                .createCompilerInstanceByName(id);
                                        for (NetworkPlugin np : loadedPlugins) {
                                            if (np.getTargetedLanguages().contains(compiler.getID())) {
                                                compiler.addNetworkPlugin(np);
                                            }
                                        }
                                        for (SerializationPlugin sp : loadedSerPlugins) {
                                            if (sp.getTargetedLanguages().contains(compiler.getID())) {
                                                compiler.addSerializationPlugin(sp);
                                            }
                                        }
                                        compiler.setOutputDirectory(
                                                new File(System.getProperty("java.io.tmpdir") + "/ThingML_temp/"
                                                        + cfg.getName()));
                                        compiler.compileConnector(connectorCompiler.getKey(), cfg);
                                    }
                                }
                            });
                        }
                    } else {
                        newCompilersMenu.add(item);
                    }

                    item.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println("Input file : " + targetFile);
                            if (targetFile == null)
                                return;
                            try {
                                ThingMLModel thingmlModel = ThingMLCompiler.loadModel(targetFile);
                                for (Configuration cfg : ThingMLHelpers.allConfigurations(thingmlModel)) {
                                    final ThingMLCompiler compiler = registry.createCompilerInstanceByName(id);
                                    for (NetworkPlugin np : loadedPlugins) {
                                        if (np.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addNetworkPlugin(np);
                                        }
                                    }
                                    for (SerializationPlugin sp : loadedSerPlugins) {
                                        if (sp.getTargetedLanguages().contains(compiler.getID())) {
                                            compiler.addSerializationPlugin(sp);
                                        }
                                    }

                                    File myFileBuf = new File(System.getProperty("java.io.tmpdir")
                                            + "/ThingML_temp/" + cfg.getName());
                                    compiler.setOutputDirectory(myFileBuf);
                                    compiler.compile(cfg);

                                    final InputStream input = new FileInputStream(myFileBuf.getAbsolutePath()
                                            + "/" + cfg.getName() + "/" + cfg.getName() + ".pde");

                                    //System.out.println("tmp file: " + myFileBuf.getAbsolutePath() + "/" + cfg.getName() + "/" + cfg.getName() + ".pde");

                                    //final InputStream input = new FileInputStream(myFileBuf);
                                    String result = null;
                                    try {
                                        if (input != null) {
                                            result = org.apache.commons.io.IOUtils.toString(input);
                                            input.close();
                                            transferBuf.setString(result);
                                            transferBuf.hasChanged();
                                            transferBuf.notifyObservers();
                                        } else {
                                            //System.out.println("WHY");
                                        }
                                    } catch (Exception exce) {
                                        if (ThingMLApp.debug)
                                            System.out.println("OH REALLY?");
                                    }

                                }
                            } catch (Exception ex) {
                                if (ThingMLApp.debug)
                                    ex.printStackTrace();
                            }
                        }
                    });
                    c = null;
                }
            }

            menubar.add(newCompilersMenu);
        }

        codeEditor.getDocument().addDocumentListener(new DocumentListener() {
            public void removeUpdate(DocumentEvent e) {
                lastUpdate.set(System.currentTimeMillis());
                checkNeeded.set(true);
            }

            public void insertUpdate(DocumentEvent e) {
                lastUpdate.set(System.currentTimeMillis());
                checkNeeded.set(true);
            }

            public void changedUpdate(DocumentEvent e) {
                lastUpdate.set(System.currentTimeMillis());
                checkNeeded.set(true);
            }
        });

        java.util.Timer timer = new Timer();
        timer.scheduleAtFixedRate(new SeamlessNotification(), 250, 250);

    } catch (Exception e) {
        if (ThingMLApp.debug)
            e.printStackTrace();
    }
}

From source file:com.company.millenium.iwannask.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    ;/*from  w  w  w. j av a 2  s. c  om*/
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
    if (DetectConnection.checkInternetConnection(this)) {
        //  myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        myWebView.reload();
    }
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
    }
    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);
}

From source file:org.wso2.carbon.wsdl2form.WSDL2FormGenerator.java

private synchronized void updateMockProxyServiceGroup(AxisService axisService, ConfigurationContext configCtx,
        AxisConfiguration axisConfig) throws AxisFault {
    /*axisService.addParameter("supportSingleOperation", Boolean.TRUE);
    AxisOperation singleOP = new InOutAxisOperation(new QName("invokeTryItProxyService"));
    singleOP.setDocumentation("This operation is a 'passthrough' for all operations in " +
                          " TryIt proxy service.");
    axisService.addOperation(singleOP);*/
    ProxyMessageReceiver receiver = new ProxyMessageReceiver(configCtx);
    PhasesInfo phaseInfo = axisConfig.getPhasesInfo();
    for (Iterator i = axisService.getOperations(); i.hasNext();) {
        AxisOperation op = (AxisOperation) i.next();
        op.setMessageReceiver(receiver);
        phaseInfo.setOperationPhases(op);
    }//  w w  w.  j  a va  2 s .  c o  m
    AxisServiceGroup serviceGroup;
    synchronized (axisConfig) {
        serviceGroup = axisConfig.getServiceGroup(TRYIT_SG_NAME);
        if (serviceGroup == null) {
            serviceGroup = new AxisServiceGroup();
            serviceGroup.setServiceGroupName(TRYIT_SG_NAME);
            serviceGroup.addParameter("DoAuthentication", "false");
            serviceGroup.addParameter("adminService", "true");
        }

        // resolving Axis service name conflicts.
        AxisService testService = axisConfig.getService(axisService.getName());
        if (testService != null) {
            for (int loop = 1;; loop++) {
                String testName = axisService.getName() + "_" + loop;
                if (axisConfig.getService(testName) == null) {
                    axisService.setName(testName);
                    break;
                }
            }
        }
        serviceGroup.addService(axisService);
        axisConfig.addServiceGroup(serviceGroup);
        axisService.addParameter(LAST_TOUCH_TIME, System.currentTimeMillis());
        axisService.addParameter("modifyUserWSDLPortAddress", "false");
        // Set the timer.
        Parameter parameter = axisConfig.getParameter(PROXY_TIMER);
        if (parameter == null) {
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(new ProxyTimerTask(axisConfig), PERIOD, PERIOD);
            parameter = new Parameter(PROXY_TIMER, timer);
            axisConfig.addParameter(parameter);
        }
    }
}

From source file:dk.netarkivet.archive.bitarchive.distribute.BitarchiveServer.java

/**
 * The server creates an instance of the bitarchive it provides access to
 * and starts to listen to JMS messages on the incomming jms queue
 * <p/>/*w  w w  . java  2  s . c o  m*/
 * Also, heartbeats are sent out at regular intervals to the Bitarchive
 * Monitor, to tell that this bitarchive is alive.
 *
 * @throws UnknownID        - if there was no heartbeat frequency or temp
 *                            dir defined in settings or if the
 *                            bitarchiveid cannot be created.
 * @throws PermissionDenied - if the temporary directory or the file
 *                            directory cannot be written
 */
private BitarchiveServer() throws UnknownID, PermissionDenied {
    System.setOut(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.INFO, log, "StdOut: ")));
    System.setErr(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.WARN, log, "StdErr: ")));
    boolean listening = false; // are we listening to queue ANY_BA
    File serverdir = FileUtils.getTempDir();
    if (!serverdir.exists()) {
        serverdir.mkdirs();
    }
    if (!serverdir.canWrite()) {
        throw new PermissionDenied("Not allowed to write to temp directory '" + serverdir + "'");
    }
    log.info("Storing temporary files at '" + serverdir.getPath() + "'");

    bitarchiveAppId = createBitarchiveAppId();

    allBa = Channels.getAllBa();
    anyBa = Channels.getAnyBa();
    baMon = Channels.getTheBamon();
    ba = Bitarchive.getInstance();
    con = JMSConnectionFactory.getInstance();
    con.setListener(allBa, this);
    baa = BitarchiveAdmin.getInstance();
    if (baa.hasEnoughSpace()) {
        con.setListener(anyBa, this);
        listening = true;
    } else {
        log.warn("Not enough space to guarantee store -- not listening " + "to " + anyBa.getName());
    }

    // create map for batchjobs
    batchProcesses = Collections.synchronizedMap(new HashMap<String, Thread>());

    // Create and start the heartbeat sender
    Timer timer = new Timer(true);
    heartBeatSender = new HeartBeatSender(baMon, this);
    long frequency = Settings.getLong(ArchiveSettings.BITARCHIVE_HEARTBEAT_FREQUENCY);
    timer.scheduleAtFixedRate(heartBeatSender, 0, frequency);
    log.info("Heartbeat frequency: '" + frequency + "'");
    // Next logentry depends on whether we are listening to ANY_BA or not
    String logmsg = "Created bitarchive server listening on: " + allBa.getName();
    if (listening) {
        logmsg += " and " + anyBa.getName();
    }

    log.info(logmsg);

    log.info("Broadcasting heartbeats on: " + baMon.getName());
}

From source file:sysnetlab.android.sdc.ui.CreateExperimentActivity.java

public void runTimer_ExperimentRunFragment() {
    mTextView = (TextView) mExperimentRunFragment.getView().findViewById(R.id.textview_experiment_run_timer);
    mTextView.setText("00:00:00");
    Timer T = new Timer();
    T.scheduleAtFixedRate(new TimerTask() {
        int seconds = 0;
        long startMilliSeconds = new Date().getTime();

        @Override/*  w  w w . jav  a  2 s. c om*/
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    seconds = (int) ((new Date().getTime() - startMilliSeconds) / 1000);
                    int hr = seconds / 3600;
                    int rem = seconds % 3600;
                    int min = rem / 60;
                    int sec = rem % 60;
                    String hrStr = (hr < 10 ? "0" : "") + hr;
                    String mnStr = (min < 10 ? "0" : "") + min;
                    String secStr = (sec < 10 ? "0" : "") + sec;
                    mTextView.setText(hrStr + ":" + mnStr + ":" + secStr);
                }
            });
        }
    }, 250, 250);
}

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;//from   w  ww  . j  a  v  a2  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:edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestService.java

/**
 * Start rss change timer.//from  ww w .  jav  a  2 s . c  o m
 */
public void startRssChangeTimer() {
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            checkForUpdates(bioportalRssFeedClient.getBioportalRssFeed());
        }

    }, 0, ONE_MINUTE * this.cacheUpdatePeriod);
}

From source file:com.company.millenium.iwannask.MainActivity.java

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

    //GPS//from   w  ww.  j  a  v a 2s . c om
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

From source file:br.unicamp.cst.util.MindViewer.java

public void StartTimer() {
    Timer t = new Timer();
    WOVTimerTask tt = new WOVTimerTask(this);
    t.scheduleAtFixedRate(tt, 0, 3000);
}

From source file:org.apache.hadoop.ipc.DecayRpcScheduler.java

/**
 * Create a decay scheduler.//from   www. j av a  2 s. c o  m
 * @param numLevels number of priority levels
 * @param ns config prefix, so that we can configure multiple schedulers
 *           in a single instance.
 * @param conf configuration to use.
 */
public DecayRpcScheduler(int numLevels, String ns, Configuration conf) {
    if (numLevels < 1) {
        throw new IllegalArgumentException("Number of Priority Levels must be " + "at least 1");
    }
    this.numLevels = numLevels;
    this.namespace = ns;
    this.decayFactor = parseDecayFactor(ns, conf);
    this.decayPeriodMillis = parseDecayPeriodMillis(ns, conf);
    this.identityProvider = this.parseIdentityProvider(ns, conf);
    this.thresholds = parseThresholds(ns, conf, numLevels);
    this.backOffByResponseTimeEnabled = parseBackOffByResponseTimeEnabled(ns, conf);
    this.backOffResponseTimeThresholds = parseBackOffResponseTimeThreshold(ns, conf, numLevels);

    // Setup response time metrics
    responseTimeTotalInCurrWindow = new AtomicLongArray(numLevels);
    responseTimeCountInCurrWindow = new AtomicLongArray(numLevels);
    responseTimeAvgInLastWindow = new AtomicDoubleArray(numLevels);
    responseTimeCountInLastWindow = new AtomicLongArray(numLevels);

    topUsersCount = conf.getInt(DECAYSCHEDULER_METRICS_TOP_USER_COUNT,
            DECAYSCHEDULER_METRICS_TOP_USER_COUNT_DEFAULT);
    Preconditions.checkArgument(topUsersCount > 0,
            "the number of top users for scheduler metrics must be at least 1");

    // Setup delay timer
    Timer timer = new Timer();
    DecayTask task = new DecayTask(this, timer);
    timer.scheduleAtFixedRate(task, decayPeriodMillis, decayPeriodMillis);

    metricsProxy = MetricsProxy.getInstance(ns, numLevels);
    metricsProxy.setDelegate(this);
}