Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:net.frygo.findmybuddy.GCMIntentService.java

private static void generateAcceptfriendNotification(Context context, String message, String status) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    if (status.equalsIgnoreCase("accept"))
        message = message + " added you as buddy";
    else/*ww w  .  ja v a  2  s.c  o m*/
        message = message + " rejected you as buddy";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    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:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

/**
 * Delay starting of polling by 5 minutes to allow original clone
 *
 * @param proj/* w w w . j av  a2s. com*/
 * @param scmTrigger
 */
private static void delayPollingStart(final FreeStyleProject proj, final SCMTrigger scmTrigger) {
    long delayStartPolling = 1000L * 60 * 5;//5 minute
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            scmTrigger.start(proj, false);
        }
    }, delayStartPolling);
}

From source file:com.symbian.driver.plugins.comms.stat.StatProcess.java

/**
 * Starts a timer to terminate a job when the TimeOut has occured if Timeout
 * is greater than 0//from   w w w  .ja  va 2  s.  c  o  m
 * 
 * @param aTimeout
 *            The length of time before the job should be canceled.
 * @return The Timer object which controls the timeout.
 */
private static Timer startTimer(final int aTimeout) {
    try {
        TIMEOUT_MAX = TDConfig.getInstance().getPreferenceInteger(TDConfig.TOTAL_TIMEOUT);
    } catch (ParseException lParseException) {
        // ignore , we have a default value.
    }
    Timer lTimeoutTimer = new Timer(false);
    lTimeoutTimer.schedule(new TimerTask() {
        public void run() {
            LOGGER.log(Level.SEVERE, "Time out : " + aTimeout + " ms reached.");
            STOP = true;
        }
    }, (aTimeout == 0) ? TIMEOUT_MAX : aTimeout);

    return lTimeoutTimer;
}

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/*from  w  w w  .  j a va 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:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command/*from w w  w . j  ava  2  s.  c  o m*/
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:com.symbian.driver.plugins.ftptelnet.TelnetProcess.java

private static Timer startTelnetTimer(final int aTimeout) {
    Timer lTimeoutTimer = new Timer("Telnet client Timer", false);
    iStopReading = false;/*from   w ww .ja v a 2 s.  co  m*/
    lTimeoutTimer.schedule(new TimerTask() {
        public void run() {
            iStopReading = true;
        }
    }, aTimeout);
    return lTimeoutTimer;
}

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/*  w  ww.j  a  v a  2 s  .  co m*/
 * @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:edu.stanford.muse.launcher.Splash.java

private static void basicSetup(String[] args) throws ParseException {
    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();//from  ww  w .  ja  v a 2 s .c  o  m
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ePADD batch mode", options);
        return;
    }

    debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open") || System.getProperty("nobrowseropen") != null)
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");

    if (!cmd.hasOption("no-shutdown")) {
        // arrange to kill Muse after a period of time, we don't want the server to run forever

        // i clearly have too much time on my hands right now...
        long secs = KILL_AFTER_MILLIS / 1000;
        long hh = secs / 3600;
        long mm = (secs % 3600) / 60;
        long ss = secs % (60);
        out.print("ePADD will shut down automatically after ");
        if (hh != 0)
            out.print(hh + " hours ");
        if (mm != 0 || (hh != 0 && ss != 0))
            out.print(mm + " minutes");
        if (ss != 0)
            out.print(ss + " seconds");
        out.println();

        Timer timer = new Timer();
        TimerTask tt = new ShutdownTimerTask();
        timer.schedule(tt, KILL_AFTER_MILLIS);
    }
    System.setSecurityManager(null); // this is important   
}

From source file:srvserver.thExecFTP.java

@Override
public void run() {
    System.out.println("Ejecutando FTP");
    Timer t1 = new Timer();

    t1.schedule(new task(), 20000);

}

From source file:srvserver.thExecLOR.java

@Override
public void run() {
    System.out.println("Ejecutando LOR");
    Timer t1 = new Timer();

    t1.schedule(new task(), 20000);

}