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:dk.netarkivet.common.utils.ProcessUtils.java

/** Wait for the end of a process, but only for a limited time.  This
 * method takes care of the ways waitFor can get interrupted.
 *
 * @param p Process to wait for/*from   w  w w.ja  v a2s  . com*/
 * @param maxWait The maximum number of milliseconds to wait for the
 * process to exit.
 * @return Exit value for process, or null if the process didn't exit
 * within the expected time.
 */
public static Integer waitFor(final Process p, long maxWait) {
    ArgumentNotValid.checkNotNull(p, "Process p");
    ArgumentNotValid.checkPositive(maxWait, "long maxWait");
    long startTime = System.currentTimeMillis();
    Timer timer = new Timer(true);
    final Thread waitThread = Thread.currentThread();
    boolean wakeupScheduled = false;
    final AtomicBoolean doneWaiting = new AtomicBoolean(false);
    while (System.currentTimeMillis() < startTime + maxWait) {
        try {
            if (!wakeupScheduled) {
                // First time in here, we need to start the wakup thread,
                // but be sure it doesn't notify us too early or too late.
                synchronized (waitThread) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            synchronized (waitThread) {
                                if (!doneWaiting.get()) {
                                    waitThread.interrupt();
                                }
                            }
                        }
                    }, maxWait);
                    wakeupScheduled = true;
                }
            }

            p.waitFor();
            break;
        } catch (InterruptedException e) {
            // May happen for a number of reasons.  We just check if we've
            // timed out yet when we go through the loop again.
        }
    }
    synchronized (waitThread) {
        timer.cancel();
        doneWaiting.set(true);
        Thread.interrupted(); // In case the timer task interrupted.
    }
    try {
        return p.exitValue();
    } catch (IllegalThreadStateException e) {
        log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime)
                + " milliseconds");
        return null;
    }
}

From source file:com.piggate.samples.PiggateLoginService.Activity_Logged.java

@Override
protected void onResume() {
    super.onResume();
    handledClick = false;/*from w  w w . j  ava2 s.  c om*/
    timer = new Timer();
    timer2 = new Timer();
    timer.schedule(new TimerTask() { //Load offers data from the server using a request
        @Override
        public void run() {
            _piggate.refreshOffers(); //Refresh the offers for every Beacon calling the server every "timer" seconds
        }
    }, 0, 10000);
    timer2.schedule(new TimerTask() { //The offers were shown by timer callback
        @Override
        public void run() {
            showUINotification(_piggate.getOffers()); //Show notifications where are offers nearby
        }
    }, 0, 15000);
}

From source file:kr.co.cashqc.MainActivity.java

public void findLocation() {
    mDialog.show();/*from  www  .  ja  v a 2s .  c  om*/
    mLocationUtil.start();
    TimerTask timerTask = new TimerTask() {
        public void run() {
            mHandler.post(new Runnable() {
                public void run() {
                    try {
                        String address;
                        address = mLocationUtil.getAddress(mLocationUtil.getLastLocation().getLatitude(),
                                mLocationUtil.getLastLocation().getLongitude());

                        // Log.d("tag", mAddressText.getText().toString() +
                        // " "
                        // + mAddressText.getText().toString().length());

                        mAddressText.setVisibility(View.VISIBLE);

                        mLatitude = mLocationUtil.getLastLocation().getLatitude();
                        mLongitude = mLocationUtil.getLastLocation().getLongitude();

                        mAddressText.setText(address);

                        mGpsFlag = true;

                        mDialog.dismiss();
                    } catch (NullPointerException e) {
                        Log.d("JAY", "gps exception");
                        e.printStackTrace();

                        mAddressText.setText("<-  ?   ? .");

                        mDialog.dismiss();

                        mGpsFlag = false;
                    }
                }
            });
        }
    };

    if (mLocationUtil.isRunLocationUtil) {
        mLocationUtil.stop();
    }

    Timer timer = new Timer();
    timer.schedule(timerTask, 1000);
}

From source file:com.piggate.samples.PiggateLogin.Activity_Logged.java

@Override
protected void onResume() {
    super.onResume();
    handledClick = false;/*ww  w  .  j a v  a2 s .  c om*/
    timer = new Timer();
    timer2 = new Timer();
    timer.schedule(new TimerTask() { //Load offers data from the server using a request
        @Override
        public void run() {
            _piggate.refreshOffers();
        }
    }, 0, 3000);
    timer2.schedule(new TimerTask() { //The offers were shown by timer callback
        @Override
        public void run() {
            showUINotification(_piggate.getOffers()); //Show notifications where are offers nearby
        }
    }, 0, 15000);
}

From source file:kieker.tools.resourceMonitor.ResourceMonitor.java

@Override
protected boolean performTask() {
    LOG.info(this.toString());

    final CountDownLatch cdl = new CountDownLatch(1);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override//from  w w  w  . j  a v a  2  s .  c o m
        public void run() {
            cdl.countDown();
        }
    });

    final Configuration controllerConfiguration;
    if (this.monitoringConfigurationFile != null) {
        controllerConfiguration = ConfigurationFactory
                .createConfigurationFromFile(this.monitoringConfigurationFile);
    } else {
        controllerConfiguration = ConfigurationFactory.createSingletonConfiguration();
    }
    this.monitoringController = MonitoringController.createInstance(controllerConfiguration);

    this.initSensors();
    LOG.info("Monitoring started");

    if (this.duration >= 0) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                cdl.countDown();
                timer.cancel();
            }
        }, TimeUnit.MILLISECONDS.convert(this.duration, this.durationUnit));
        LOG.info("Waiting for " + this.duration + " " + this.durationUnit + " timeout...");
    }

    try {
        LOG.info("Press Ctrl+c to terminate");
        cdl.await();
    } catch (final InterruptedException ex) {
        LOG.warn("The monitoring has been interrupted", ex);
        return false;
    } finally {
        LOG.info("Monitoring terminated");
    }

    return true;
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

/**
 * Constructs a new MetricsReporter./* w  w w . j  a  v  a 2s .c  o  m*/
 *
 * @param reportingPeriod
 *            the metrics reporting period in seconds
 * @param reportingDelay
 *            delay (in seconds) before first metrics reporting is invoked
 */
public MetricsReporter(int reportingPeriod, Integer reportingDelay) {
    tracker = initTracker();
    TimerTask mrt = new TimerTask() {
        @Override
        public void run() {
            reportMetrics(topicsMetrics);
        }
    };
    long period = TimeUnit.SECONDS.toMillis(reportingPeriod);
    long delay = reportingDelay == null ? period : TimeUnit.SECONDS.toMillis(reportingDelay);
    LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
            "MetricsReporter.schedule.reporting", delay, period);
    metricsReportingTimer = new java.util.Timer();
    metricsReportingTimer.scheduleAtFixedRate(mrt, delay, period);
}

From source file:pl.openrnd.connection.rest.ConnectionHandler.java

private Timer startRequestTimer(final Request request) {
    Timer result = new Timer();
    result.schedule(new TimerTask() {
        @Override/*w  w w.  j a  va2 s  .c o m*/
        public void run() {
            notifyTakingTooLong(request);
        }
    }, mConnectionConfig.getRequestWarningTime());
    return result;
}

From source file:jahirfiquitiva.iconshowcase.fragments.WallpapersFragment.java

private static void setupLayout(final boolean fromTask, final Activity context, final ImageView noConnection) {

    if (WallpapersList.getWallpapersList() != null && WallpapersList.getWallpapersList().size() > 0) {
        context.runOnUiThread(new Runnable() {
            @Override/* w w w.  j  a  v  a 2 s .  c o m*/
            public void run() {
                mAdapter = new WallpapersAdapter(context, new WallpapersAdapter.ClickListener() {
                    @Override
                    public void onClick(WallpapersAdapter.WallsHolder view, int position, boolean longClick) {
                        if ((longClick && !ShowcaseActivity.wallsPicker) || ShowcaseActivity.wallsPicker) {
                            final MaterialDialog dialog = new MaterialDialog.Builder(context)
                                    .content(R.string.downloading_wallpaper).progress(true, 0).cancelable(false)
                                    .show();

                            WallpaperItem wallItem = WallpapersList.getWallpapersList().get(position);

                            Glide.with(context).load(wallItem.getWallURL()).asBitmap()
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(final Bitmap resource,
                                                GlideAnimation<? super Bitmap> glideAnimation) {
                                            if (resource != null) {
                                                new ApplyWallpaper(context, dialog, resource,
                                                        ShowcaseActivity.wallsPicker, layout).execute();
                                            }
                                        }
                                    });
                        } else {
                            final Intent intent = new Intent(context, ViewerActivity.class);

                            intent.putExtra("item", WallpapersList.getWallpapersList().get(position));
                            intent.putExtra("transitionName", ViewCompat.getTransitionName(view.wall));

                            Bitmap bitmap;

                            if (view.wall.getDrawable() != null) {
                                bitmap = Utils.drawableToBitmap(view.wall.getDrawable());

                                try {
                                    String filename = "temp.png";
                                    FileOutputStream stream = context.openFileOutput(filename,
                                            Context.MODE_PRIVATE);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                                    stream.close();
                                    intent.putExtra("image", filename);
                                } catch (Exception e) {
                                    Utils.showLog(context, "Error getting drawable " + e.getLocalizedMessage());
                                }

                                ActivityOptionsCompat options = ActivityOptionsCompat
                                        .makeSceneTransitionAnimation(context, view.wall,
                                                ViewCompat.getTransitionName(view.wall));
                                context.startActivity(intent, options.toBundle());
                            } else {
                                context.startActivity(intent);
                            }
                        }
                    }
                });

                mAdapter.setData(WallpapersList.getWallpapersList());

                mRecyclerView.setAdapter(mAdapter);

                fastScroller = (RecyclerFastScroller) layout.findViewById(R.id.rvFastScroller);

                fastScroller.attachRecyclerView(mRecyclerView);

                if (fastScroller.getVisibility() != View.VISIBLE) {
                    fastScroller.setVisibility(View.VISIBLE);
                }

                if (Utils.hasNetwork(context)) {
                    hideProgressBar();
                    noConnection.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                    fastScroller.setVisibility(View.VISIBLE);
                    mSwipeRefreshLayout.setEnabled(false);
                    mSwipeRefreshLayout.setRefreshing(false);
                } else {
                    hideStuff(noConnection);
                }
            }
        });
    } else {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (layout != null) {
                    noConnection.setVisibility(View.GONE);
                    showProgressBar();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideStuff(noConnection);
                                }
                            });
                        }
                    }, 7500);
                }
            }
        });
    }
}

From source file:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java

/**
 * Starts the heartbeat./*from   w  w  w. j a  v a 2  s .c  om*/
 *
 * @param websocket The websocket the heartbeat should be sent to.
 * @param heartbeatInterval The heartbeat interval.
 * @return The timer used for the heartbeat.
 */
private Timer startHeartbeat(final WebSocket websocket, final int heartbeatInterval) {
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            /* if (heartbeatAckReceived) { temporally removed */
            heartbeatAckReceived = false;
            sendHeartbeat(websocket);
            logger.debug("Sent heartbeat (interval: {})", heartbeatInterval);
            /*} else {
            logger.info("We did not receive an answer to our last heartbeat. Trying to reconnect!");
            websocket.sendClose(1002);
            }*/
        }
    }, 0, heartbeatInterval);
    return timer;
}

From source file:org.openhab.habdroid.ui.OpenHABDiscoveryFragment.java

private void activateDiscovery(String id) {
    if (mAsyncHttpClient != null) {
        startProgressIndicator();/*  w  w w . j  av a  2  s  .  c o  m*/
        mAsyncHttpClient.post(getActivity(), openHABBaseUrl + "rest/discovery/bindings/" + id + "/scan", null,
                "text/plain", new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        Log.d(TAG, "Activate discovery request success");
                        if (discoveryTimer != null) {
                            discoveryTimer.cancel();
                            discoveryTimer.purge();
                            discoveryTimer = null;
                        }
                        discoveryTimer = new Timer();
                        discoveryTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                Log.d(TAG, "Discovery timer ended");
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            stopProgressIndicator();
                                            if (mActivity != null) {
                                                mActivity.openDiscoveryInbox();
                                            }
                                        }
                                    });
                                }
                            }
                        }, 10000);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
                            Throwable error) {
                        stopProgressIndicator();
                        Log.e(TAG, "Activate discovery request error: " + error.getMessage());
                    }
                });
    }
}