Example usage for java.util Timer scheduleAtFixedRate

List of usage examples for java.util Timer scheduleAtFixedRate

Introduction

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

Prototype

public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

Usage

From source file:net.czlee.debatekeeper.AlertManager.java

/**
 * Starts a single strobe flash, i.e., one rapid period of flashing.  So in a double strobe
 * bell, there are two of these.//from  w  w w  .ja  va 2  s  .  co m
 * @param flashTime how long in milliseconds the strobe flash should last
 * @param colour colour to flash screen
 * @param lastFlash <code>true</code> if the GUI should be reset after this strobe flash
 */
private void startSingleStrobeFlashScreen(long flashTime, final int colour, final boolean lastFlash) {
    Timer strobeTimer = new Timer();

    int numberOfStrobes = (int) (flashTime / STROBE_PERIOD);
    if (flashTime % STROBE_PERIOD > STROBE_PERIOD / 2)
        numberOfStrobes++;
    final int numStrobes = numberOfStrobes;

    if (numStrobes == 0)
        return; // Do nothing if the number of bells is zero

    /* Note: To avoid race conditions, we do NOT have a single TimerTask to toggle the
     * screen flash at a fixed rate.  We have one timer to govern turning the screen on
     * at a fixed repeat period.  Each time the screen starts a flash, a *separate* timer
     * is started to turn the screen off.  This guarantees (hopefully) that the last timer
     * task that affects the screen is always one that turns it off.
     */

    strobeTimer.scheduleAtFixedRate(new TimerTask() {
        int timesSoFar = 0;

        @Override
        public void run() {
            if (++timesSoFar < numStrobes) {
                startSingleFlashScreen(STROBE_PERIOD * 2 / 3, colour, false);
            } else {
                // If it's the last flash in this strobe *and* this strobe was the last strobe
                // flash in the sequence, then pass true to lastFlash of startSingleFlashScreen.
                startSingleFlashScreen(STROBE_PERIOD * 2 / 3, colour, lastFlash);
                this.cancel();
            }
        }
    }, 0, STROBE_PERIOD);
}

From source file:com.usertaxi.TaxiOntheWay_Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiontheway);

    taxiOntheWay_activity_instance = this;
    AppPreferences.setApprequestTaxiScreen(TaxiOntheWay_Activity.this, true);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);//www . j a  v a 2  s.  c  o m
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);
    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    FloatingActionButton fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    FloatingActionButton fab_call = (FloatingActionButton) findViewById(R.id.fab_call);
    FloatingActionButton fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textheader = (TextView) findViewById(R.id.textheader);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    textheader.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);

    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    Log.d("data value", data + "");

    //caceldialog();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(data);
        AppPreferences.setAcceptdriverId(TaxiOntheWay_Activity.this, jsonObject.getString("driverId"));
        Log.d("driverid---", AppPreferences.getAcceptdriverId(TaxiOntheWay_Activity.this));
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        //driverlatitude = jsonObject.getDouble("latitude");
        //driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        //            Log.d("longitudeeeee:------", String.valueOf(jsonObject.getDouble("longitude")));

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        final MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        //  marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        //taxiname.setText(drivertaxiname);

        Intent intent1 = new Intent(TaxiOntheWay_Activity.this, DriverService.class);
        intent1.putExtra("driverId", jsonObject.getString("driverId"));
        startService(intent1);

        if (driverimage.equalsIgnoreCase("")) {
            mdriverimage.setImageResource(R.drawable.ic_action_user);
        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);
        }

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                        /* try{
                             String url = Function.getDirectionsUrl(new LatLng(Double.parseDouble(AppPreferences.getPreviouslat(getApplicationContext())),
                                     Double.parseDouble(AppPreferences.getPreviouslong(getApplicationContext()))),
                                     new LatLng(Double.parseDouble(AppPreferences.getCurrentlat(getApplicationContext())),
                                             Double.parseDouble(AppPreferences.getCurrentlong(getApplicationContext()))));
                             RoutesDownloadTask downloadTask = new RoutesDownloadTask(TaxiOntheWay_Activity.this);
                             downloadTask.execute(url);
                         }catch(Exception e)
                         {
                             e.printStackTrace();
                         }*/
                    }
                });
            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    /////////////notification dataend///////////////

    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });
    fab_call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + drivermobile));
            startActivity(callIntent);
        }
    });

    moveMarkerList = new ArrayList<LatLng>();
    //        moveRoadMarker();
}

From source file:org.wso2.carbon.core.init.CarbonServerManager.java

private void registerHouseKeepingTask(ConfigurationContext configurationContext) {
    if (Boolean.valueOf(serverConfig.getFirstProperty("HouseKeeping.AutoStart"))) {
        Timer houseKeepingTimer = new Timer();
        long houseKeepingInterval = Long.parseLong(serverConfig.getFirstProperty("HouseKeeping.Interval")) * 60
                * 1000;/*from w ww .ja v a  2 s  . c  o m*/
        Object property = configurationContext.getProperty(ServerConstants.FILE_RESOURCE_MAP);
        if (property == null) {
            property = new TreeBidiMap();
            configurationContext.setProperty(ServerConstants.FILE_RESOURCE_MAP, property);
        }
        houseKeepingTimer.scheduleAtFixedRate(new HouseKeepingTask(serverWorkDir, (BidiMap) property),
                houseKeepingInterval, houseKeepingInterval);
    }
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override//from   ww  w. j  a  v  a  2s  . co  m
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}

From source file:net.czlee.debatekeeper.AlertManager.java

/**
 * Flashes the screen according to the specifications of a bell.
 * @param bsi the {@link BellSoundInfo} for this bell
 *//*from  ww  w. j  a  v  a2 s.c o  m*/
private void flashScreen(BellSoundInfo bsi, final int colour) {
    Timer repeatTimer = new Timer();
    final long repeatPeriod = bsi.getRepeatPeriod();
    final int timesToPlay = bsi.getTimesToPlay();
    if (timesToPlay == 0)
        return; // Do nothing if the number of bells is zero

    if (mFlashScreenListener == null)
        return;

    // Try to acquire a semaphore; if we can't, return immediately and don't bother
    // with the flash screen
    if (!mFlashScreenListener.begin())
        return;

    wakeUpScreenForBell(repeatPeriod * timesToPlay);

    /* Note: To avoid race conditions, we do NOT have a single TimerTask to toggle the
     * screen flash at a fixed rate.  We have one timer to govern turning the screen on
     * at a fixed repeat period.  Each time the screen starts a flash, a *separate* timer
     * is started to turn the screen off.  This guarantees (hopefully) that the last timer
     * task that affects the screen is always one that turns it off.
     */

    repeatTimer.scheduleAtFixedRate(new TimerTask() {
        int timesSoFar = 0;

        @Override
        public void run() {
            long flashTime = repeatPeriod / 2;

            // If half the repeat period is more than the maximum flash time, or if this is
            // the last repetition, make the flash time equal to the maximum
            if (flashTime > MAX_BELL_SCREEN_FLASH_TIME)
                flashTime = MAX_BELL_SCREEN_FLASH_TIME;

            final boolean lastFlash = ++timesSoFar >= timesToPlay;
            if (lastFlash) {
                flashTime = MAX_BELL_SCREEN_FLASH_TIME;
                this.cancel();
            }

            switch (mFlashScreenMode) {
            case SOLID_FLASH:
                startSingleFlashScreen(flashTime, colour, lastFlash);
                break;
            case STROBE_FLASH:
                startSingleStrobeFlashScreen(flashTime, colour, lastFlash);
                break;
            case OFF:
                // Do nothing
                break;
            }

        }
    }, 0, repeatPeriod);
}

From source file:me.rojo8399.placeholderapi.impl.Metrics.java

private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override/*from w w  w .  j  a  v  a 2 s  .  c  om*/
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even
            // possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still
            // async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give
    // other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be
    // blocked/deleted!
    // WARNING: Just don't do it!
}

From source file:com.smartmarmot.dbforbix.config.Config.java

private void launchSchedulers(Set<String> configurationUIDs) {
    for (String configurationUID : configurationUIDs) {
        if (!workTimers.containsKey(configurationUID)) {
            Timer workTimer = new Timer(configurationUID);
            workTimers.put(configurationUID, workTimer);
            int i = 0;
            for (Entry<Integer, Scheduler> element : getSchedulersByConfigurationUID(configurationUID)
                    .entrySet()) {/*from   w  w w  .  j ava  2s  .co  m*/
                LOG.info("creating worker(" + configurationUID + ") for timing: " + element.getKey());
                i++;
                workTimer.scheduleAtFixedRate(element.getValue(), 500 + i * 500,
                        (long) (element.getKey() * 1000));
            }
            //            try {
            //               //Thread.sleep(5000);
            //            } catch (InterruptedException e) {
            //               e.printStackTrace();
            //            }
        }
    }
}

From source file:com.diversityarrays.kdxplore.design.EntryFileImportDialog.java

public EntryFileImportDialog(Window owner, String title, File inputFile, Predicate<Role> entryHeadingFilter) {
    super(owner, title, ModalityType.APPLICATION_MODAL);

    this.entryHeadingFilter = entryHeadingFilter;
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    setGlassPane(backgroundRunner.getBlockingPane());

    useScrollBarOption.addActionListener(new ActionListener() {
        @Override/*  w  w  w.  j av  a 2  s.c o  m*/
        public void actionPerformed(ActionEvent e) {
            updateDataPreviewScrolling();
        }
    });

    headingRoleTableModel = createHeadingRoleTableModel();
    headingRoleTable = new HeadingRoleTable<>(headingRoleTableModel);
    headingTableScrollPane = new JScrollPane(headingRoleTable);
    GuiUtil.setVisibleRowCount(headingRoleTable, 10);

    JPanel roleAssignmentPanel = new JPanel(new BorderLayout());
    roleAssignmentPanel.add(headingTableScrollPane, BorderLayout.CENTER);

    headingRoleTable.setTransferHandler(flth);
    headingRoleTableModel.addChangeListener(headingRoleChangeListener);

    GuiUtil.setVisibleRowCount(dataPreviewTable, 10);
    dataPreviewTable.setTransferHandler(flth);
    dataPreviewScrollPane.setTransferHandler(flth);
    updateDataPreviewScrolling();

    dataPreviewScrollPane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            //                boolean useScrollBar = useScrollBarOption.isSelected();
            GuiUtil.initialiseTableColumnWidths(dataPreviewTable, true);
        }
    });

    Box top = Box.createHorizontalBox();
    top.add(new JLabel("# rows to preview: "));
    top.add(new JSpinner(previewRowCountSpinnerModel));
    top.add(Box.createHorizontalGlue());
    top.add(useScrollBarOption);

    JPanel dataPreviewPanel = new JPanel(new BorderLayout());
    dataPreviewPanel.add(GuiUtil.createLabelSeparator("Data Preview", top), BorderLayout.NORTH);
    dataPreviewPanel.add(dataPreviewScrollPane, BorderLayout.CENTER);

    headingWarning.setForeground(Color.RED);
    JLabel instructions = new JLabel("<HTML>Please assign a <i>Role</i> for each of the headings in your data"
            + "<br>You must specify one as the <i>Entry Name</i>."
            + "<br>Click on one of the <i>Role</i> cells and select from the dropdown"
            + "<br>To assign multiple headings, select the rows for which you wish"
            + "<br>to set the <i>Role</i> then right-click and choose from the dropdown.");
    instructions.setHorizontalAlignment(JLabel.CENTER);
    instructions.setBackground(Toast.PALE_YELLOW);

    JScrollPane instScroll = new JScrollPane(instructions);
    instScroll.setBackground(Toast.PALE_YELLOW);

    normalEntryNameField.getDocument()
            .addDocumentListener(new DocumentChangeListener((e) -> updateAcceptButton()));
    normalEntryNameField.setText(TrialDesignPreferences.getInstance().getNormalEntryTypeName());

    JPanel rolesPanel = new JPanel();
    GBH gbh = new GBH(rolesPanel, 2, 2, 0, 0);
    int y = 0;
    gbh.add(0, y, 1, 1, GBH.NONE, 0, 1, GBH.EAST, "Entry Type Name for non-Checks:");
    gbh.add(1, y, 1, 1, GBH.NONE, 1, 1, GBH.WEST, normalEntryNameField);
    gbh.add(2, y, 1, 1, GBH.NONE, 1, 1, GBH.WEST, saveForFuture);
    ++y;

    gbh.add(0, y, 3, 1, GBH.BOTH, 2, 1, GBH.CENTER, roleAssignmentPanel);
    ++y;

    JSplitPane headingsAndInstructions = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, rolesPanel, instScroll);

    JPanel headingPanel = new JPanel(new BorderLayout());
    headingPanel.add(GuiUtil.createLabelSeparator("Assign Roles for Headings"), BorderLayout.NORTH);
    headingPanel.add(headingsAndInstructions, BorderLayout.CENTER);
    headingPanel.add(headingWarning, BorderLayout.SOUTH);

    errorMessage.setEditable(false);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, dataPreviewPanel, headingPanel);
    splitPane.setResizeWeight(0.5);

    cardPanel.add(new JScrollPane(errorMessage), CARD_ERROR);
    cardPanel.add(splitPane, CARD_DATA);

    Box bot = Box.createHorizontalBox();
    bot.add(Box.createHorizontalGlue());
    bot.add(new JButton(cancelAction));
    bot.add(new JButton(acceptAction));
    acceptAction.setEnabled(false);

    Container cp = getContentPane();
    cp.add(cardPanel, BorderLayout.CENTER);
    cp.add(bot, BorderLayout.SOUTH);
    pack();

    sheetNamesComboBox.addActionListener(sheetNamesActionListener);

    Timer timer = new Timer(true);

    previewRowCountSpinnerModel.addChangeListener(new ChangeListener() {
        int nPreview;
        TimerTask timerTask = null;

        @Override
        public void stateChanged(ChangeEvent e) {
            nPreview = previewRowCountSpinnerModel.getNumber().intValue();

            if (timerTask == null) {
                timerTask = new TimerTask() {
                    int lastPreviewCount = nPreview;

                    @Override
                    public void run() {
                        if (lastPreviewCount == nPreview) {
                            System.err.println("Stable at " + lastPreviewCount);
                            // No change, do it now
                            cancel();
                            try {
                                updateDataPreview(lastPreviewCount);
                            } finally {
                                timerTask = null;
                            }
                        } else {
                            System.err.println("Changing from " + lastPreviewCount + " to " + nPreview);
                            lastPreviewCount = nPreview;
                        }
                    }
                };
                timer.scheduleAtFixedRate(timerTask, 500, 100);
            }
        }
    });

    sheetNamesComboBox.setVisible(false);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
            removeWindowListener(this);
            setFile(inputFile);
        }
    });
}

From source file:self.philbrown.javaQuery.$.java

/**
 * Schedule a task for repeated fixed-rate execution after a specific delay has passed.
 * @param the task to schedule. Receives no args. Note that the function will be
 * run on a Timer thread, and not the UI Thread.
 * @param delay amount of time in milliseconds before execution.
 * @return the created Timer/*  w  ww.  ja v a2  s. c  o  m*/
 */
public static Timer setInterval(final Function function, long delay) {
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            function.invoke(null);
        }

    }, 0, delay);
    return t;
}

From source file:coffeshop.PaymentPage.java

private void btcTimer() {
    Timer timer = new Timer(); //new timer
    timeExpired = false;/*from ww  w .  ja v a 2 s. com*/
    TimerTask task = new TimerTask() {
        int counter = 10;

        public void run() {
            int minutes = 0;
            int seconds = 0;
            minutes = counter / 60;
            seconds = counter % 60;
            if (timeStop) {
                timer.cancel();
                timer.purge();
            } else {
                String timeString = String.format("Time Left: %02d:%02d", minutes, seconds);
                lblTimer.setText(timeString);
                counter--;
                if (counter == -1) {
                    timer.cancel();
                    timer.purge();
                    lblTimer.setText("Time Expired");
                    timeExpired = true;
                    lblQRC.setIcon(defaultQR);
                }
            }

        }
    };
    timer.scheduleAtFixedRate(task, 1000, 1000);
}