Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

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

Prototype

public Timer() 

Source Link

Document

Creates a new timer.

Usage

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 .jav  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:org.openhab.habdroid.ui.OpenHABDiscoveryFragment.java

private void activateDiscovery(String id) {
    if (mAsyncHttpClient != null) {
        startProgressIndicator();/*from ww  w .j  av  a  2 s .c  om*/
        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());
                    }
                });
    }
}

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  . com*/
            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: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:com.snappy.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///w  w  w.j  a v a 2 s. c o  m
private void generateNotification(Context context, String message, String fromName, Bundle pushExtras,
        String body) {

    db = new LocalDB(context);
    List<LocalMessage> myMessages = db.getAllMessages();

    // Open a new activity called GCMMessageView
    Intent intento = new Intent(this, SplashScreenActivity.class);
    intento.replaceExtras(pushExtras);
    // Pass data to the new activity
    intento.putExtra(Const.PUSH_INTENT, true);
    intento.setAction(Long.toString(System.currentTimeMillis()));
    intento.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

    // Starts the activity on notification click
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intento, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification with a notification builder
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon_notification).setWhen(System.currentTimeMillis())
            .setContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message))
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Mas mensajes")).setAutoCancel(true)
            .setDefaults(
                    Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
            .setContentText(body).setContentIntent(pIntent);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message));

    for (int i = 0; i < myMessages.size(); i++) {

        inboxStyle.addLine(myMessages.get(i).getMessage());
    }

    notification.setStyle(inboxStyle);

    // Remove the notification on click
    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;
    //notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.defaults |= Notification.DEFAULT_LIGHTS;

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification.build());
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        final PowerManager.WakeLock mWakelock = pm
                .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();
        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
    }
}

From source file:cl.tide.fm.sensonet.SensonetClient.java

private void checkingNetwork() {
    netTimer = new Timer();
    netTimer.schedule(new TimerTask() {
        @Override// w w w  . jav a  2  s  . c o m
        public void run() {
            boolean status = netIsAvailable();
            if (status != isOnline) {
                isOnline = status;
                System.out.println("Network " + status);
                if (listener != null) {
                    listener.isOnline(isOnline);
                }
            }
        }
    }, 0, 5000);
}

From source file:src.com.nustats.pacelogger.RecordingActivity.java

@Override
public void onResume() {
    super.onResume();

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override//from   ww w  .j  a v a  2  s .c o  m
        public void run() {
            mHandler.post(mUpdateTimer);
        }
    }, 0, 1000); // every second
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 * Start polling. Reason is for debugging only
 *///from  www  .  ja  va2 s . c o  m

private void startPolling(String reason) {
    Log.d("SecureChat", "Polling because " + reason);

    if (timer == null) {
        timer = new Timer();
    }
    timerTask = new TimerTask() {
        @Override
        public void run() {
            pollForMessages();
        }
    };

    timer.schedule(timerTask, 0, POLLRATE);
}

From source file:jp.pigumer.sso.WebSecurityConfig.java

public ExtendedMetadataDelegate extendedMetadataProvider() throws Exception {
    ResourceBackedMetadataProvider metadataProvider = new ResourceBackedMetadataProvider(new Timer(),
            new ClasspathResource(properties.getIdpMetaFile()));
    metadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(metadataProvider,
            extendedMetadata());/*  w w  w.j  a  v  a  2  s  .c  om*/
    extendedMetadataDelegate.setMetadataTrustCheck(false);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

From source file:coria2015.server.JsonRPCMethods.java

/**
     * Shutdown the server/*from   w ww.java2  s  .c o  m*/
     */
    @RPCMethod(help = "Shutdown Experimaestro server")
    public boolean shutdown() {
        // Shutdown jetty (after 1s to allow this thread to finish)
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                boolean stopped = false;
                try {
                    server.stop();
                    stopped = true;
                } catch (Exception e) {
                    LOGGER.warning("Could not stop properly jetty");
                }
                if (!stopped)
                    synchronized (this) {
                        try {
                            wait(10000);
                        } catch (InterruptedException e) {
                            LOGGER.severe(e.toString());
                        }
                        System.exit(1);

                    }
            }
        }, 2000);

        // Everything's OK
        return true;
    }