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.sftoolworks.nfcoptions.SelectActivity.java

protected void writeSelection(Intent intent) {
    ListView list = (ListView) findViewById(R.id.listView1);
    if (list.getCount() == 0)
        return;/*w  ww. j  a v a  2 s  . c o  m*/

    try {

        Object[] results = ((OptionListAdapter) list.getAdapter()).getCheckedValues();
        JSONObject obj = new JSONObject();

        JSONArray array = new JSONArray();

        if (null != results) {
            for (Object result : results)
                array.put(result.toString());
        }

        obj.put("selection", array);
        obj.put("key", selectKey);

        SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key),
                Context.MODE_PRIVATE);

        // android studio (0.5.1) decorates this line as an error (some
        // of the time, anyway) but it's not an error.

        String identifier = sharedPref.getString(getString(R.string.user_id_key), "");
        if (identifier.length() > 0)
            obj.put("user", identifier);

        String json = obj.toString(0);

        String outbound = "\u0002en";
        outbound += json;

        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, new byte[] { 'T' }, null,
                outbound.getBytes());

        NdefMessage message = new NdefMessage(new NdefRecord[] { textRecord });
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        ndef.connect();

        ndef.writeNdefMessage(message);
        ndef.close();

        Toast.makeText(this, R.string.write_ok, Toast.LENGTH_LONG).show();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);

    } catch (Exception e) {

        Log.d(TAG, e.toString());
        String err = getString(R.string.tag_write_err) + "\n" + e.getMessage();
        Toast.makeText(this, err, Toast.LENGTH_LONG).show();
    }
}

From source file:uk.org.openseizuredetector.MainActivity.java

/** Called when the activity is first created. */
@Override//from ww  w . j  a v a 2  s  .  co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialise the User Interface
    setContentView(R.layout.main);

    /* Force display of overflow menu - from stackoverflow
     * "how to force use of..."
     */
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
        Log.v(TAG, "menubar fiddle exception: " + e.toString());
    }

    // start timer to refresh user interface every second.
    Timer uiTimer = new Timer();
    uiTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            updateServerStatus();
        }
    }, 0, 1000);

}

From source file:org.apache.james.ESReporterTest.java

@Test
public void timeMetricsShouldBeReportedWhenJmapRequestsReceived() throws Exception {
    TimerTask timerTask = new TimerTask() {
        @Override//from w  w  w.j a va 2 s  . c  o  m
        public void run() {
            try {
                given().header("Authorization", accessToken.serialize())
                        .body("[[\"getMailboxes\", {}, \"#0\"]]").with().post("/jmap");
            } catch (Exception e) {
                LOGGER.error("Error while listing mailboxes", e);
            }
        }
    };
    timer.schedule(timerTask, DELAY_IN_MS, PERIOD_IN_MS);

    await().atMost(Duration.TEN_MINUTES).until(() -> checkMetricRecordedInElasticSearch());
}

From source file:com.nokia.example.musicexplorer.ui.SearchView.java

/**
 * Delays the search and cancels a possible pending search.
 */// w  ww.j  a v a  2  s  .c o m
private void throttleSearch() {
    if (throttle != null) {
        // Cancel previous timer task.
        throttle.cancel();
    }

    throttle = new Timer();
    throttle.schedule(new TimerTask() {
        public void run() {
            performSearch(true, false); // Clear previous results. No paging.
            cancel();
        }
    }, QUERY_THROTTLE_MILLISECONDS);
}

From source file:com.datatorrent.lib.bucket.AbstractTimeBasedBucketManager.java

@Override
public void startService(Listener<T> listener) {
    bucketSlidingTimer = new Timer();
    endOBucketsInMillis = expiryTime + (noOfBuckets * bucketSpanInMillis);
    logger.debug("bucket properties {}, {}", daysSpan, bucketSpanInMillis);
    logger.debug("bucket time params: start {}, expiry {}, end {}", startOfBucketsInMillis, expiryTime,
            endOBucketsInMillis);/*w  ww. j  ava 2 s.  com*/

    bucketSlidingTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            long time;
            synchronized (lock) {
                time = (expiryTime += bucketSpanInMillis);
                endOBucketsInMillis += bucketSpanInMillis;
                if (recordStats) {
                    bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOBucketsInMillis);
                    bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryTime);
                }
            }
            try {
                ((BucketStore.ExpirableBucketStore<T>) bucketStore).deleteExpiredBuckets(time);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }, bucketSpanInMillis, bucketSpanInMillis);
    super.startService(listener);
}

From source file:com.willwinder.universalgcodesender.model.GUIBackend.java

private void scheduleTimers() {
    autoConnectTimer.scheduleAtFixedRate(new TimerTask() {
        private int count = 0;

        @Override/*from w ww.j  a v  a 2 s.  co  m*/
        public void run() {
            //autoconnect();

            // Move the mouse every 30 seconds to prevent sleeping.
            if (isPaused() || isActive()) {
                count++;
                if (count % 10 == 0) {
                    keepAwake();
                    count = 0;
                }
            }
        }
    }, 1000, 1000);
}

From source file:de.xirp.io.comm.lowlevel.AbstractStreamCommunicationInterface.java

/**
 * Constructs a timer task which will send the given data array.
 * /*  www  .ja  v a2 s  .  co  m*/
 * @param data
 *            byte array which will be send
 * @return the task to use within a timer
 */
private TimerTask getSendPeriodicTask(final byte[] data) {
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            if (connected) {
                send(data);
            }
        }
    };
    return task;
}

From source file:org.eclipse.swt.examples.watchdog.TimedEventWatchdog.java

public TimedEventWatchdog(Thread uiThread, long threshold_ms) {
    if (uiThread == null) {
        throw new NullPointerException();
    }/*from  www .  j a  va  2s . c  o m*/

    this.threshold_ms = threshold_ms;
    this.dataCollectionDelay = threshold_ms / 2;

    this.uiThread = uiThread;
    this.timer = new Timer("Monitoring data collection timer", true);
    this.onTickTask = new TimerTask() {
        @Override
        public void run() {
            poll();
        }
    };

    grabStackAt = Long.MAX_VALUE;
    timer.scheduleAtFixedRate(onTickTask, 0, Math.max(dataCollectionDelay / 2, 1));
}

From source file:es.curso.android.arduino.Main.java

private void launchTimerTask() {

    mTempTimer = new Timer();

    mTempTimer.scheduleAtFixedRate(new TimerTask() {
        @Override/*  w  w w  .  ja  v  a  2 s . co  m*/
        public void run() {
            String response = doPetition(URL + "status/");
            JSONObject json = parseJSON(response);
            showData(json);

        }
    }, 0, UPDATED_TIME);

}

From source file:dk.netarkivet.wayback.aggregator.AggregationWorker.java

/**
 * Starts the aggregation task. Only allowed to be called once to avoid aggregation race conditions.
 *//*from   w ww. j a v a  2s  . c o m*/
private void startAggregationThread() {
    if (aggregatorTask == null) {
        aggregatorTask = new TimerTask() {
            @Override
            public void run() {
                runAggregation();
            }
        };
        Timer aggregatorThreadTimer = new Timer("AggregatorThread");
        aggregatorThreadTimer.schedule(aggregatorTask, 0,
                Settings.getLong(WaybackSettings.WAYBACK_AGGREGATOR_AGGREGATION_INTERVAL));
    } else {
        throw new IllegalStateException("An attempt has been made to start a second aggregation job");
    }
}