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:org.texai.torrent.TrackerTest.java

/**
 * Test of bit torrent tracker.//from   w ww .j  a v  a 2  s. c o  m
 */
@Test
public void testTracker() {
    LOGGER.info("tracker");

    // configure the HTTP request handler by registering the tracker
    final HTTPRequestHandler httpRequestHandler = HTTPRequestHandler.getInstance();
    final Tracker tracker = new Tracker();
    tracker.addInfoHash(new String((new URLCodec()).encode(INFO_HASH)));
    httpRequestHandler.register(tracker);

    // configure the server channel pipeline factory
    final AbstractBitTorrentHandlerFactory bitTorrentHandlerFactory = new MockBitTorrentHandlerFactory();
    final AbstractHTTPRequestHandlerFactory httpRequestHandlerFactory = new HTTPRequestHandlerFactory();
    final X509SecurityInfo x509SecurityInfo = KeyStoreTestUtils.getServerX509SecurityInfo();
    final ChannelPipelineFactory channelPipelineFactory = new PortUnificationChannelPipelineFactory(null, // albusHCNMessageHandlerFactory,
            bitTorrentHandlerFactory, httpRequestHandlerFactory, x509SecurityInfo);

    // configure the server
    final ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    assertEquals("{}", serverBootstrap.getOptions().toString());
    serverBootstrap.setPipelineFactory(channelPipelineFactory);

    // bind and start to accept incoming connections
    serverBootstrap.bind(new InetSocketAddress("localhost", SERVER_PORT));

    // test tracker client
    httpClient();

    final Timer timer = new Timer();
    timer.schedule(new ShutdownTimerTask(), 5000);

    // shut down executor threads to exit
    LOGGER.info("releasing server resources");
    serverBootstrap.releaseExternalResources();
    timer.cancel();
}

From source file:cl.smartcities.isci.transportinspector.dialogs.BusSelectionDialog.java

@NonNull
@Override/*from ww w.  j av a 2  s  .c  o  m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog dialog;
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

    LayoutInflater inflater = this.getActivity().getLayoutInflater();
    final View dialog_view = inflater.inflate(R.layout.bus_selection_dialog, null);
    final Typeface iconTypeface = Typeface.createFromAsset(this.getContext().getAssets(),
            getActivity().getString(R.string.icon_font));
    ((TextView) dialog_view.findViewById(R.id.suggestion_icon)).setTypeface(iconTypeface);

    builder.setView(dialog_view);
    builder.setCancelable(false);
    dialog = builder.create();

    final Bundle bundle = getArguments();
    ArrayList<Bus> buses = null;

    if (bundle != null) {
        buses = bundle.getParcelableArrayList(NotificationState.BUSES);
    }

    if (buses != null && !buses.isEmpty()) {
        dialog_view.findViewById(R.id.list_view).setVisibility(View.VISIBLE);
        setBusMap(buses);
        ArrayList<String> serviceList = new ArrayList<>();
        serviceList.addAll(this.busMap.keySet());
        BusSelectionAdapter adapter = new BusSelectionAdapter(this.getContext(), serviceList, busMap,
                new BusSelectionAdapter.ListViewAdapterListener() {
                    @Override
                    public void onPositiveClick(Bus bus) {
                        dialog.cancel();
                        listener.onPositiveClick(bus);
                    }

                    @Override
                    public void onNegativeClick() {
                        dialog.cancel();
                        listener.onNegativeClick();
                    }
                });
        ListView listView = (ListView) dialog_view.findViewById(R.id.list_view);

        listView.setAdapter(adapter);

        if (adapter.getCount() > VISIBLE_BUSES) {
            View item = adapter.getView(0, null, listView);
            item.measure(0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    (int) ((VISIBLE_BUSES + 0.5) * item.getMeasuredHeight()));
            listView.setLayoutParams(params);
        }

    }

    Button otherAcceptButton = (Button) dialog_view.findViewById(R.id.accept);
    otherAcceptButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText serviceEditText = (EditText) dialog_view.findViewById(R.id.service_edit_text);
            EditText licensePlateEditText = (EditText) dialog_view.findViewById(R.id.license_plate_edit_text);
            String service = serviceEditText.getText().toString();
            String licensePlate = licensePlateEditText.getText().toString();
            ServiceHelper helper = new ServiceHelper(getContext());

            if (ServiceValidator.validate(service) && helper.getColorId(Util.formatServiceName(service)) != 0) {
                service = Util.formatServiceName(service);
                if (licensePlate.equals("")) {
                    licensePlate = Constants.DUMMY_LICENSE_PLATE;
                } else if (!LicensePlateValidator.validate(licensePlate)) {
                    Toast.makeText(getContext(), R.string.bus_selection_warning_plate, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
            } else {
                Toast.makeText(getContext(), R.string.bus_selection_warning_service, Toast.LENGTH_SHORT).show();
                return;
            }

            final Bus bus = new Bus(Util.formatServiceName(service), licensePlate);
            InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

            Log.d("BusSelectionDialog", "hiding soft input");

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    BusSelectionDialog.this.getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.cancel();
                            listener.onPositiveClick(bus);
                        }
                    });
                }
            }, 500);
            //dialog.cancel();
            // TODO(aantoine): This call is to quick, some times the keyboard is not
            // out of the window when de sliding panel shows up.
            //listener.onPositiveClick(bus);
        }
    });

    /* set cancel button to close dialog */
    dialog_view.findViewById(R.id.close_dialog).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.cancel();
            listener.onNegativeClick();
        }
    });
    ((Button) dialog_view.findViewById(R.id.close_dialog)).setTypeface(iconTypeface);
    dialog.setCanceledOnTouchOutside(false);

    return dialog;
}

From source file:idgs.client.TcpClient.java

/**
 * //  w  w  w  .ja  va  2 s . c o  m
 * @param timeout
 * @param retryTimes
 * @throws IOException
 */
public boolean connect(final boolean enableTimeoutCheck, final int timeout, final int retryTimes) {
    if (enableTimeoutCheck) {
        if (retryTimes <= 0) { // up to re-try times
            return isConnected();
        }
        Timer timer = new Timer(); // after timeout seconds, run timer task, if not connected, re-try again
        timer.schedule(new TimerTask() {
            public void run() {
                if (!isConnected()) {
                    int newRetryTimes = retryTimes - 1;
                    connect(enableTimeoutCheck, timeout, newRetryTimes);
                }
            }
        }, timeout);
    }
    try {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_CONNECT);
        channel.connect(servAddr);
        select();
    } catch (IOException e) {
        log.warn("try to connecte to server[" + servAddr.toString() + "] error, " + e.getMessage());
    }
    return isConnected();
}

From source file:org.gw4e.eclipse.facade.GraphWalkerFacade.java

public static List<IFile> generateOffLineFromFile1(IWorkbenchWindow ww, TestResourceGeneration dcp,
        BuildPolicy[] generators, int timeout, IProgressMonitor monitor)
        throws IOException, CoreException, InterruptedException {
    IFile graphModel = dcp.getGraphIFile();

    List<IFile> ret = new ArrayList<IFile>();

    List<Context> executionContexts = new ArrayList<Context>();
    for (BuildPolicy policy : generators) {
        String startElement = getStartElement(dcp.getGraphFile());
        Path path = dcp.getInputPath();
        String generator = policy.getPathGenerator();
        String msg = "Offline arguments: " + path + " " + generator + " " + startElement;
        ResourceManager.logInfo(graphModel.getProject().getName(), msg);
        addContexts(executionContexts, path, generator, startElement);
    }//from  w w w .  j  a va 2s  .c  om

    int index = 0;
    for (Context context : executionContexts) {
        OfflineContext oc = new OfflineContext(generators[index]);
        index++;
        dcp.addOfflineContext(oc);
        TestExecutor executor = new TestExecutor(context);
        executor.getMachine().addObserver(new Observer() {
            @Override
            public void update(Machine machine, Element element, EventType type) {
                if (EventType.BEFORE_ELEMENT.equals(type)) {
                    oc.addMethodName(element.getName());
                    if (monitor.isCanceled()) {
                        throw new RuntimeException(
                                new InterruptedException(MessageUtil.getString("timeoutofflineorcancelled")));
                    }
                }
            }
        });

        Timer canceller = new Timer();
        canceller.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    monitor.setCanceled(true);
                } catch (Throwable e) {
                }
            }

        }, timeout * 1000);

        try {
            Result result = executor.execute();
            canceller.cancel();
        } catch (TestExecutionException e) {

            String reason = e.getResult().getResultsAsString();
            canceller.cancel();
            ResourceManager.logException(e, reason);

            if (!ErrorDialog.AUTOMATED_MODE) { // Avoid displaying a window while running automated mode
                DialogManager.asyncDisplayErrorMessage(MessageUtil.getString("error"), reason, e);
            }
        } catch (Throwable e) {
            canceller.cancel();
            ResourceManager.logException(e);
            if (!ErrorDialog.AUTOMATED_MODE) { // Avoid displaying a window while running automated mode
                DialogManager.asyncDisplayErrorMessage(MessageUtil.getString("error"),
                        MessageUtil.getString("an_error_occured_while_running_offline_tool"), e);
            }
            return ret;
        }
    }
    dcp.updateWithOfflines();

    generateFromFile(ww, dcp, monitor);
    return ret;
}

From source file:deincraftlauncher.IO.download.Downloader.java

private void update() {

    System.out.println("downloader update #" + updateNum);
    updateNum++;/*www  .  ja  v  a2 s. co  m*/

    if (instance.finished) {
        System.out.println("cancelling updating");
        return;
    }

    onUpdate.call(totalProgress, totalSize, this);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            //periodic update
            timer.cancel();
            timer.purge();
            update();
        }
    }, updateDelay);

}

From source file:org.apache.sling.testing.serversetup.jarexec.ShutdownHookSingleProcessDestroyer.java

public void destroyProcess(boolean waitForIt) {
    Process toDestroy = null;// w  w w.j av  a2 s.  co m
    synchronized (this) {
        toDestroy = process;
        process = null;
    }

    if (toDestroy == null) {
        return;
    }

    toDestroy.destroy();

    if (waitForIt) {
        log.info("Waiting for destroyed process {} to exit (timeout={} seconds)", processInfo, timeoutSeconds);
        final Thread mainThread = Thread.currentThread();
        final Timer t = new Timer(true);
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                mainThread.interrupt();
            }
        };
        t.schedule(task, timeoutSeconds * 1000L);
        try {
            toDestroy.waitFor();
            try {
                final int exit = toDestroy.exitValue();
                log.info("Process {} ended with exit code {}", processInfo, exit);
            } catch (IllegalStateException ise) {
                log.error("Failed to destroy process " + processInfo);
            }
        } catch (InterruptedException e) {
            log.error("Timeout waiting for process " + processInfo + " to exit");
        } finally {
            t.cancel();
        }
    }
}

From source file:org.apache.unomi.geonames.services.GeonamesServiceImpl.java

public void importDatabase() {
    if (!persistenceService.createIndex("geonames")) {
        if (forceDbImport) {
            persistenceService.removeIndex("geonames");
            persistenceService.createIndex("geonames");
            logger.info("Geonames index removed and recreated");
        } else if (persistenceService.getAllItemsCount(GeonameEntry.ITEM_TYPE) > 0) {
            return;
        }//from   ww  w .j  a  v a  2  s  . c o  m
    } else {
        logger.info("Geonames index created");
    }

    if (pathToGeonamesDatabase == null) {
        logger.info("No geonames DB provided");
        return;
    }
    final File f = new File(pathToGeonamesDatabase);
    if (f.exists()) {
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(f));
                    ZipEntry zipEntry = zipInputStream.getNextEntry();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream, "UTF-8"));

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String line;
                    logger.info("Starting to import geonames database ...");
                    while ((line = reader.readLine()) != null) {
                        String[] values = line.split("\t");

                        if (FEATURES_CLASSES.contains(values[6])) {
                            GeonameEntry geonameEntry = new GeonameEntry(values[0], values[1], values[2],
                                    StringUtils.isEmpty(values[4]) ? null : Double.parseDouble(values[4]),
                                    StringUtils.isEmpty(values[5]) ? null : Double.parseDouble(values[5]),
                                    values[6], values[7], values[8], Arrays.asList(values[9].split(",")),
                                    values[10], values[11], values[12], values[13],
                                    StringUtils.isEmpty(values[14]) ? null : Integer.parseInt(values[14]),
                                    StringUtils.isEmpty(values[15]) ? null : Integer.parseInt(values[15]),
                                    values[16], values[17], sdf.parse(values[18]));

                            persistenceService.save(geonameEntry);
                        }
                    }
                    logger.info("Geonames database imported");
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }, 5000);
    }
}

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 .ja v  a  2  s.co  m*/
        public void run() {
            notifyTakingTooLong(request);
        }
    }, mConnectionConfig.getRequestWarningTime());
    return result;
}

From source file:deincraftlauncher.IO.download.FTPDownloader.java

@Override
public void start() {

    if (!prepared) {
        prepare();//from www  .  ja  v a 2s.c  om
    }

    if (preparing) {
        try {
            prepareThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (started) {
        return;
    }

    started = true;

    System.out.println("starting ftp download: " + fileName);

    finished = false;
    updateNum = 0;

    downloadThread = new Thread() {
        @Override
        public void run() {

            System.out.println("FTPDownload Thread started");

            File targetPath = new File(saveTo);
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }

            saveTo += fileName;

            System.out.println("Starting Download; Link=" + link + " saveTo=" + saveTo);

            //Actual download code
            try {
                OutputStream output = new FileOutputStream(saveTo);
                CountingOutputStream cos = new CountingOutputStream(output) {

                    boolean updateReady = true;

                    @Override
                    protected void beforeWrite(int n) {
                        super.beforeWrite(n);

                        if (!updateReady) {
                            return;
                        }

                        totalProgress = this.getCount() / totalSize;

                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                updateReady = true;
                            }
                        }, updateDelay);

                        updateReady = false;
                    }
                };
                update();

                FTPConnection.getClient().retrieveFile(ftpfile.getName(), cos);

                cos.close();
                output.close();
                onFinished.call(instance);
                onFinishedB.call(instance);
                finished = true;
                System.out.println("Download fertig");
                started = false;
                //download fertig
                downloadThread.interrupt();

            } catch (IOException ex) {
                System.err.println("error while downliading via ftp: " + ex);
            }

        }
    };

    downloadThread.start();
    started = false;

}

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

private void startChkTimer() {
    mFlag = false;//ww  w  . j  a v a 2 s  . c  o  m
    mChkTimer = new Timer(TIMER_CHECK_ACC);
    mChkTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (isOn() && !mFlag) {
                MyLog.e(LociConfig.D.SYS, TAG,
                        "[ACC] (check timer) Movement Detector is not receiving Accel data. restart handler.");

                if (isOn())
                    stop();

                Timer restartTimer = new Timer(TIMER_RESTART_ACC);
                restartTimer.schedule(new TimerTask() {
                    public void run() {
                        MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Restart Accelerometer.");
                        start();
                    }
                }, 500);

            } else {
                MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Movement Detector OK.");
            }
            mFlag = false;
        }
    }, LociConfig.pAccWatch, LociConfig.pAccWatch);
}