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:org.pentaho.di.ui.spoon.trans.StepPerformanceSnapShotDialog.java

public void open() {

    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
    props.setLook(shell);/* w  ww.j  a v a 2  s.co  m*/
    shell.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Title"));
    shell.setImage(GUIResource.getInstance().getImageLogoSmall());

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout(formLayout);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    dataList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(0, 0);
    fdDataList.bottom = new FormAttachment(30, 0);
    dataList.setLayoutData(fdDataList);

    stepsList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(dataList, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(shell, SWT.NONE);
    props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(props.getMiddlePct() / 2, 0);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, 0);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    shell.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    shell.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    Timer timer = new Timer("step performance snapshot dialog Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java

public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost,
        float substitutionCost, float omissionCost, Distance distance) {
    // build first row
    List<Float> row = range(transWord.length() + 1);

    // results/* w  ww  .  j  ava2 s  .  c  o  m*/
    Set<SuggestionResult> results = new HashSet<SuggestionResult>();

    // iteratively (to prevent stack overflow) search each branch of the graph
    // a stack of paths to traverse. This prevents the StackOverflowException.
    Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>();
    for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) {
        long child = iter.next();
        char c = getChar(child);

        StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(),
                String.valueOf(c), row);
        stack.push(entry);
    }

    // thread to control time to search for suggestions
    mAreTimeAvailable = true;
    mTimerTask = new TimerTask() {

        @Override
        public void run() {
            //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!");
            mAreTimeAvailable = false;
        }
    };
    mTimer = new Timer();
    mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions

    while (!stack.empty() && mAreTimeAvailable) {
        StackLevenshteinEntry entry = stack.pop();
        List<Float> previousRow = entry.previousRow;

        int columns = entry.chars.length + 1;
        List<Float> currentRow = new LinkedList<Float>();
        currentRow.add(previousRow.get(0) + omissionCost);

        // build one row for the letter, with a column for each letter in the target word, 
        // plus one for the empty string at column 0
        for (int column = 1; column < columns; column++) {
            // cost * braille_distance
            float insertCost = currentRow.get(column - 1) + insertionCost;// * 
            //getInsertionDistance(entry.chars, column-1, getChar(entry.node));
            float omitCost = previousRow.get(column) + omissionCost;
            float substituteCost = previousRow.get(column - 1);

            if (entry.chars[column - 1] != getChar(entry.node))
                substituteCost += substitutionCost
                        * distance.getDistance(entry.chars[column - 1], getChar(entry.node));

            currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost)));
        }

        // if last entry in the row indicates the optimal cost is less than the maximum cost,
        // and there is a word in this node, then add it.
        int last = currentRow.size() - 1;
        if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) {
            results.add(new SuggestionResult(entry.subword, currentRow.get(last)));
        }

        // if any entries in the row are less than the maximum cost, then iteratively search each branch
        if (min(currentRow) <= maxCost) {
            for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) {
                // get child
                long child = iter.next();

                // build subword
                StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars,
                        entry.subword + getChar(child), currentRow);

                // search that branch
                stack.push(nextEntry);
            }
        }
    }

    mTimer.cancel();

    // return list of results
    return results;
}

From source file:com.data.pack.ViewVideo.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.videoplay);/*from   www  .  ja  va  2s  . c  o m*/
    Intent i = getIntent();
    Bundle extras = i.getExtras();
    filename = extras.getString("workoutname");
    workoutID = extras.getString("workoutID");
    UserName = extras.getString("UserName");
    userID = extras.getString("userID");
    // l= (View)findViewById(R.id.btnnavigation);
    btnQuit = (Button) findViewById(R.id.headeQuitricon);
    // btnplay =(Button)findViewById(R.id.btnplay);
    placeData = new PlaceDataSQL(this);
    GlobalData.appcount++;
    if (arrVoVideoName == null)
        arrVoVideoName = new ArrayList<VOWorkoutVideos>();
    GlobalData.viewvideochange = 0;
    if (videoPathes == null)
        videoPathes = new ArrayList<Object>();

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;

    // params.screenBrightness = 10;
    getWindow().setAttributes(params);
    if (obUser.getSelectedLanguage().equals("1")) {
        YesString = "Yes";
        strLeaveVideo = "You are about to exit the Video. Are you sure ?";
        NoString = "No";
    } else {
        YesString = "Ja";
        QuitString = "verlassen";
        strLeaveVideo = "Du bist dabei das Video zu beenden, bist Du sicher ?";
        NoString = "Nein";
    }
    count = 1;
    // Toast.makeText(getBaseContext(), "countcountcountcount"
    // +count,Toast.LENGTH_LONG).show();
    // btnQuit =(Button) findViewById(R.id.headeQuitricon);
    btnQuit.setText(QuitString);
    btnQuit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Intent intent = new Intent(sharescreen.this,
            // HomeScreen.class);
            // // intent.putExtra("userID", userID);
            // startActivity(intent);

            AlertDialog alertDialog = new AlertDialog.Builder(ViewVideo.this).create();
            if (mVideoView.isPlaying()) {
                mVideoView.pause();
            }

            alertDialog.setTitle("fitness4.me");
            alertDialog.setMessage(strLeaveVideo);

            alertDialog.setButton(-1, YesString, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        GlobalData.viewvideochange = 1;
                        Intent intent = new Intent(ViewVideo.this, FitnessforMeActivity.class);
                        startActivity(intent);
                        if (mVideoView != null)
                            mVideoView.stopPlayback();

                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            });
            alertDialog.setButton(-2, NoString, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    GlobalData.viewvideochange = 0;

                    mVideoView.start();

                    dialog.cancel();
                }
            });
            try {
                alertDialog.show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });
    mycontroller = new MediaController(this);
    mVideoView = (VideoView) findViewById(R.id.surface_view);
    mVideoView.setMediaController(null);
    AdView adView = (AdView) this.findViewById(R.id.adView);
    if (GlobalData.allPurchased == true) {

        adView.setVisibility(View.GONE);
    } else {
        adView.setVisibility(View.VISIBLE);
        adView.loadAd(new AdRequest());

    }

    try {
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                TimerMethod();
            }

        }, 1, 1000);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    mVideoView.setOnCompletionListener(myVideoViewCompletionListener);
    getDataAndPopulate();

}

From source file:de.thm.arsnova.services.QuestionService.java

@Override
@PreAuthorize("isAuthenticated() and hasPermission(#questionId, 'question', 'owner')")
public void startNewPiRoundDelayed(final String questionId, final int time) {
    final Timer timer = new Timer();
    final Date date = new Date();
    final Date endDate = new Date(date.getTime() + (time * 1000));
    final IQuestionService questionService = this;
    final User user = userService.getCurrentUser();
    final Question question = databaseDao.getQuestion(questionId);
    final Session session = databaseDao.getSessionFromKeyword(question.getSessionKeyword());

    cancelDelayedPiRoundChange(questionId);

    timer.schedule(new TimerTask() {
        @Override/*from  w  w w . j  a  v  a 2 s  .c o  m*/
        public void run() {
            questionService.startNewPiRound(questionId, user);
        }
    }, endDate);

    timerList.put(questionId, timer);
    question.setPiRoundActive(true);
    question.setPiRoundStartTime(date.getTime());
    question.setPiRoundEndTime(endDate.getTime());
    update(question);

    this.publisher.publishEvent(new PiRoundDelayedStartEvent(this, session, question));
}

From source file:com.trsst.server.TrsstAdapter.java

/**
 * Called to trigger an asynchronous fetch, usually after we have returned
 * possibly stale data and we want to make sure it's refreshed on the next
 * pull. This implementation uses a short fuse timer task queue, but others
 * should implement a heuristic to queue this task for later based on the
 * likelihood that a refetch is needed, e.g. factoring in time since last
 * update and frequency of updates, etc.
 *///ww w  .ja  va2 s  . c  o  m
protected void pullLaterFromRelay(final String feedId, final RequestContext request) {
    if (TASK_QUEUE == null) {
        TASK_QUEUE = new Timer();
    }
    final String uri = request.getResolvedUri().toString();
    log.debug("fetchLaterFromRelay: queuing: " + uri);
    if (!COALESCING_TIMERS.containsKey(uri)) {
        log.debug("fetchLaterFromRelay: creating: " + uri);
        TimerTask task = new TimerTask() {
            public void run() {
                log.debug("fetchLaterFromRelay: starting: " + uri);
                pullFromRelay(feedId, request);
                COALESCING_TIMERS.remove(uri);
            }
        };
        COALESCING_TIMERS.put(uri, task);
        TASK_QUEUE.schedule(task, 6000); // six seconds
    }
}

From source file:de.yaacc.upnp.server.YaaccUpnpServerService.java

/**
 * /*  w  ww  .ja  v a 2 s.  c o  m*/
 */
private void initialize() {
    this.initialized = false;
    if (!getUpnpClient().isInitialized()) {
        getUpnpClient().initialize(getApplicationContext());
        watchdog = false;
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                watchdog = true;
            }
        }, 30000L); // 30 sec. watchdog

        while (!getUpnpClient().isInitialized() && !watchdog) {
            // wait for upnpClient initialization
        }
    }
    if (getUpnpClient().isInitialized()) {
        if (preferences.getBoolean(
                getApplicationContext().getString(R.string.settings_local_server_provider_chkbx), false)) {
            if (localServer == null) {
                localServer = createMediaServerDevice();
            }
            getUpnpClient().getRegistry().addDevice(localServer);

            createHttpServer();
        }

        if (preferences.getBoolean(
                getApplicationContext().getString(R.string.settings_local_server_receiver_chkbx), false)) {
            if (localRenderer == null) {
                localRenderer = createMediaRendererDevice();
            }
            getUpnpClient().getRegistry().addDevice(localRenderer);
        }
        this.initialized = true;
    } else {
        throw new IllegalStateException("UpnpClient is not initialized!");
    }

    startUpnpAliveNotifications();
}

From source file:com.timemachine.controller.ControllerActivity.java

private void runHideEditorTimer() {
    stopHideEditorTimer();/*from w w w .  ja v a 2  s .c  o  m*/
    hideEditorTimerTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    setMode("player");
                }
            });
        }
    };
    hideEditorTimer.schedule(hideEditorTimerTask, hideEditorTime);
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFarmManager.java

/**
 * Creates new form DSWorkbenchFarmManager
 *//*from   w w  w.j  av a2  s  . c o m*/
DSWorkbenchFarmManager() {
    initComponents();
    centerPanel = new GenericTestPanel();
    jCenterPanel.add(centerPanel, BorderLayout.CENTER);
    centerPanel.setChildComponent(jFarmPanel);
    buildMenu();
    jFarmTable.setModel(new FarmTableModel());
    jFarmTable.getTableHeader().setDefaultRenderer(new de.tor.tribes.ui.renderer.DefaultTableHeaderRenderer());
    ColorHighlighter p = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.BARBARIAN));
    p.setBackground(Color.LIGHT_GRAY);
    ColorHighlighter p1 = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.PLAYER));
    p1.setBackground(new Color(0xffffcc));
    jFarmTable.setHighlighters(
            HighlighterFactory.createAlternateStriping(Constants.DS_ROW_A, Constants.DS_ROW_B), p, p1);
    jFarmTable.setDefaultRenderer(Boolean.class,
            new CustomBooleanRenderer(CustomBooleanRenderer.LayoutStyle.RES_IN_STORAGE));
    jFarmTable.setDefaultRenderer(Date.class, new de.tor.tribes.ui.renderer.DateCellRenderer());
    jFarmTable.setDefaultRenderer(Float.class, new de.tor.tribes.ui.renderer.PercentCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmStatus));
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_RESULT.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmResult));
    jFarmTable.setDefaultRenderer(StorageStatus.class, new de.tor.tribes.ui.renderer.StorageCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.SIEGE_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.SiegeStatus));
    jFarmTable.setColumnControlVisible(true);
    jFarmTable.setSortsOnUpdates(false);
    FarmManager.getSingleton().addManagerListener(DSWorkbenchFarmManager.this);
    settingsPanel.setLayout(new BorderLayout());
    settingsPanel.add(jSettingsPanel, BorderLayout.CENTER);

    new Timer("FarmTableUpdate").schedule(new TimerTask() {

        @Override
        public void run() {
            jFarmTable.repaint();
        }
    }, new Date(), 1000);

    KeyStroke delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false);
    KeyStroke farmA = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false);
    KeyStroke farmB = KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, false);
    KeyStroke farmK = KeyStroke.getKeyStroke(KeyEvent.VK_K, 0, false);
    KeyStroke farmC = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0, false);
    ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            deleteSelection();
        }
    };

    capabilityInfoPanel1.addActionListener(listener);

    jFarmTable.setSortsOnUpdates(false);
    jFarmTable.registerKeyboardAction(listener, "Delete", delete,
            JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmA();
        }
    }, "FarmA", farmA, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmB();
        }
    }, "FarmB", farmB, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmK();
        }
    }, "FarmK", farmK, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmC();
        }
    }, "FarmC", farmC, JComponent.WHEN_IN_FOCUSED_WINDOW);

    aTroops = new TroopSelectionPanelDynamic();
    aTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    bTroops = new TroopSelectionPanelDynamic();
    bTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    kTroops = new TroopSelectionPanelDynamic();
    kTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    cTroops = new TroopSelectionPanelDynamic();
    cTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    rTroops = new TroopSelectionPanelDynamic();
    rTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    jATroopsPanel.add(aTroops, BorderLayout.CENTER);
    jBTroopsPanel.add(bTroops, BorderLayout.CENTER);
    jKTroopsPanel.add(kTroops, BorderLayout.CENTER);
    jCTroopsPanel.add(cTroops, BorderLayout.CENTER);
    jRSettingsTab.add(rTroops, BorderLayout.CENTER);
    jXLabel1.setLineWrap(true);

    jFarmTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            showInfo(jFarmTable.getSelectedRowCount() + " Farm(en) gewhlt");
        }
    });

    coordSpinner = new CoordinateSpinner();
    coordSpinner.setEnabled(false);
    java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
    jFarmFromBarbarianSelectionDialog.getContentPane().add(coordSpinner, gridBagConstraints);

    // <editor-fold defaultstate="collapsed" desc=" Init HelpSystem ">
    if (!Constants.DEBUG) {
        GlobalOptions.getHelpBroker().enableHelpKey(getRootPane(), "farmManager",
                GlobalOptions.getHelpBroker().getHelpSet());
    } // </editor-fold>
}

From source file:be.fgov.kszbcss.rhq.websphere.config.cache.ConfigQueryCache.java

public void start(int numThreads) {
    synchronized (cache) {
        if (threads != null || stopping) {
            // start has already been called before
            throw new IllegalStateException();
        }//w  w  w . j  a  va  2  s .c  o  m
        if (persistentFile.exists()) {
            if (log.isDebugEnabled()) {
                log.debug("Reading persistent cache " + persistentFile);
            }
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream(persistentFile));
                try {
                    for (int i = in.readInt(); i > 0; i--) {
                        ConfigQueryCacheEntry<?> entry = (ConfigQueryCacheEntry<?>) in.readObject();
                        cache.put(entry.query, entry);
                    }
                } finally {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("Failed to read persistent cache data", ex);
            } catch (ClassNotFoundException ex) {
                log.error("Unexpected exception", ex);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Starting " + numThreads + " worker threads");
    }
    threads = new Thread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        Thread thread = new Thread(this, name + "-query-" + (i + 1));
        threads[i] = thread;
        thread.start();
    }
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            persist();
        }
    }, 5 * 60 * 1000);
    // TODO: need another timer that removes entries that are no longer used!
}