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:net.resheim.eclipse.timekeeper.ui.Activator.java

private void installTaxameter() {

    switch (Platform.getOS()) {
    case Platform.OS_MACOSX:
        detector = new MacIdleTimeDetector();
        break;//from   w  w  w . j  a  v  a 2  s .c o m
    case Platform.OS_LINUX:
        detector = new X11IdleTimeDetector();
        break;
    case Platform.OS_WIN32:
        detector = new WindowsIdleTimeDetector();
        break;
    default:
        detector = new GenericIdleTimeDetector();
        break;
    }

    Timer timer = new Timer("Timekeeper", true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!PlatformUI.getWorkbench().isClosing()) {
                long idleTimeMillis = detector.getIdleTimeMillis();
                ITask task = TasksUi.getTaskActivityManager().getActiveTask();
                if (null != task) {
                    if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                        // Was idle on last check, reactivate
                        Display.getDefault().syncExec(() -> handleReactivation(idleTimeMillis));
                    } else if (lastIdleTime < IDLE_INTERVAL) {
                        String tickString = Activator.getValue(task, Activator.TICK);
                        LocalDateTime now = LocalDateTime.now();
                        LocalDateTime ticked = LocalDateTime.parse(tickString);
                        // Currently not idle so accumulate spent time
                        accumulateTime(task, now.toLocalDate().toString(),
                                ticked.until(now, ChronoUnit.MILLIS));
                        Activator.setValue(task, Activator.TICK, now.toString());
                    }
                }
                lastIdleTime = idleTimeMillis;
            }
        }
    }, SHORT_INTERVAL, SHORT_INTERVAL);

    // Immediately run the idle handler if the system has been idle and
    // the user has pressed a key or mouse button _inside_ the running
    // application.
    reactivationListener = new Listener() {
        public void handleEvent(Event event) {
            long idleTimeMillis = detector.getIdleTimeMillis();
            if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                handleReactivation(idleTimeMillis);
            }
            lastIdleTime = idleTimeMillis;
        }
    };
    final Display display = PlatformUI.getWorkbench().getDisplay();
    display.addFilter(SWT.KeyUp, reactivationListener);
    display.addFilter(SWT.MouseUp, reactivationListener);
}

From source file:com.ladinc.core.screens.GameScreenLobby.java

@Override
public void pause() {
    Gdx.app.debug("pause", "entering Pause");

    if (this.timer != null) {
        timer.cancel();/*w ww  .  ja v a  2s. co m*/
        timer.purge();
    }

    this.timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Gdx.app.debug("pause", "fake loop");

            sendPlayerHeartbeats();

            if (game.startGame) {
                Gdx.app.debug("GameScreenLobby - pause", "Start flag is true, moving to new screen");

                if (timer != null) {
                    timer.cancel();
                    timer.purge();
                }

                game.setScreen(game.gameScreen);
                game.pause();
            }
        }
    }, McpCah.BACKGROUND_REFRESH_TIME, McpCah.BACKGROUND_REFRESH_TIME);

}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override//from   ww w.j  a  v  a2  s . c  om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    suggestionsTimer = new Timer("suggestions-timer");
    countdownTimer = new Timer("messsage-countdown-timer");

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenReceiver, filter);

    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        if (cloud != null) {
            setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                    cloud, 0xFFF2F7FC));
            cloud.recycle();
        }
    }
    setContentView(R.layout.activity_message);
    try {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    } catch (Throwable t) {
    }

    suggestionsAdapter = new SuggestionsAdapter();
    progressBar = (ProgressBar) findViewById(R.id.progress);
    errorMsg = (TextView) findViewById(R.id.errorMsg);
    buffersListView = findViewById(R.id.BuffersList);
    messageContainer = (LinearLayout) findViewById(R.id.messageContainer);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    redColor = getResources().getColor(R.color.highlight_red);
    blueColor = getResources().getColor(R.color.dark_blue);

    messageTxt = (ActionEditText) findViewById(R.id.messageTxt);
    messageTxt.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
                    && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            } else if (keyCode == KeyEvent.KEYCODE_TAB) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                    nextSuggestion();
                return true;
            }
            return false;
        }
    });
    messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (drawerLayout != null && v == messageTxt && hasFocus) {
                drawerLayout.closeDrawers();
                update_suggestions(false);
            } else if (!hasFocus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        suggestionsContainer.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }
    });
    messageTxt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawerLayout != null) {
                drawerLayout.closeDrawers();
            }
        }
    });
    messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null
                    && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            }
            return true;
        }
    });
    textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            Object[] spans = s.getSpans(0, s.length(), Object.class);
            for (Object o : spans) {
                if (((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING)
                        && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class
                                || o.getClass() == BackgroundColorSpan.class
                                || o.getClass() == UnderlineSpan.class || o.getClass() == URLSpan.class)) {
                    s.removeSpan(o);
                }
            }
            if (s.length() > 0
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED) {
                sendBtn.setEnabled(true);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(1);
            } else {
                sendBtn.setEnabled(false);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(0.5f);
            }
            String text = s.toString();
            if (text.endsWith("\t")) { //Workaround for Swype
                text = text.substring(0, text.length() - 1);
                messageTxt.setText(text);
                nextSuggestion();
            } else if (suggestionsContainer != null && suggestionsContainer.getVisibility() == View.VISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        update_suggestions(false);
                    }
                });
            } else {
                if (suggestionsTimer != null) {
                    if (suggestionsTimerTask != null)
                        suggestionsTimerTask.cancel();
                    suggestionsTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                            update_suggestions(false);
                        }
                    };
                    suggestionsTimer.schedule(suggestionsTimerTask, 250);
                }
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    };
    messageTxt.addTextChangedListener(textWatcher);
    sendBtn = findViewById(R.id.sendBtn);
    sendBtn.setFocusable(false);
    sendBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED)
                new SendTask().execute((Void) null);
        }
    });

    photoBtn = findViewById(R.id.photoBtn);
    if (photoBtn != null) {
        photoBtn.setFocusable(false);
        photoBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                insertPhoto();
            }
        });
    }
    userListView = findViewById(R.id.usersListFragment);

    View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
    v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            show_topic_popup();
        }
    });

    if (drawerLayout != null) {
        if (findViewById(R.id.usersListFragment2) == null) {
            upDrawable = new DrawerArrowDrawable(this);
            greyColor = upDrawable.getColor();
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationIcon(upDrawable);
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationContentDescription("Show navigation drawer");
            drawerLayout.setDrawerListener(mDrawerListener);
            if (refreshUpIndicatorTask != null)
                refreshUpIndicatorTask.cancel(true);
            refreshUpIndicatorTask = new RefreshUpIndicatorTask();
            refreshUpIndicatorTask.execute((Void) null);
        }
    }
    messageTxt.setDrawerLayout(drawerLayout);

    title = (TextView) v.findViewById(R.id.title);
    subtitle = (TextView) v.findViewById(R.id.subtitle);
    key = (ImageView) v.findViewById(R.id.key);
    getSupportActionBar().setCustomView(v);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    if (savedInstanceState != null && savedInstanceState.containsKey("cid")) {
        server = ServersDataSource.getInstance().getServer(savedInstanceState.getInt("cid"));
        buffer = BuffersDataSource.getInstance().getBuffer(savedInstanceState.getInt("bid"));
        backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("imagecaptureuri"))
        imageCaptureURI = Uri.parse(savedInstanceState.getString("imagecaptureuri"));
    else
        imageCaptureURI = null;

    ConfigInstance config = (ConfigInstance) getLastCustomNonConfigurationInstance();
    if (config != null) {
        imgurTask = config.imgurUploadTask;
        fileUploadTask = config.fileUploadTask;
    }

    drawerLayout.setScrimColor(0);
    drawerLayout.closeDrawers();

    getSupportActionBar().setElevation(0);
}

From source file:com.vladsch.idea.multimarkdown.editor.MultiMarkdownPreviewEditor.java

protected void delayedHtmlPreviewUpdate(final boolean fullKit) {
    if (updateDelayTimer != null) {
        updateDelayTimer.cancel();//w  w  w .  j  a v a 2  s .c  o  m
        updateDelayTimer = null;
    }

    if (project.isDisposed())
        return;

    if (!isEditorTabVisible)
        return;

    updateDelayTimer = new Timer();
    updateDelayTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (project.isDisposed())
                return;

            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (project.isDisposed())
                        return;

                    previewIsObsolete = true;

                    if (fullKit) {
                        setStyleSheet();
                        //processor.remove();     // make it re-initialize when accessed
                    }

                    updateHtmlContent(isActive || isMyTabSelected());
                }
            }, ModalityState.any());
        }
    }, getUpdateDelay());
}

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

private void setupUI() {
    // Set layout listener
    View controllerView = findViewById(R.id.controllerView);
    ViewTreeObserver vto = controllerView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override//from ww  w  . j a  v  a 2  s.  c o m
        public void onGlobalLayout() {
            runOnUiThread(new Runnable() {
                public void run() {
                    locationSliderHeight = locationSlider.getHeight();
                    originLocationSliderContainerY = locationSliderContainer.getY();
                    originPlayPauseButtonY = playPause.getY();
                    minLocationSliderContainerY = originLocationSliderContainerY;
                    maxLocationSliderContainerY = originLocationSliderContainerY + locationSliderHeight;
                    midLocationSliderContainerY = (minLocationSliderContainerY + maxLocationSliderContainerY)
                            / 2;
                }
            });
            System.out.println("locationSliderHeight: " + locationSliderHeight);
            System.out.println("locationSliderContainerY: " + originLocationSliderContainerY);
            locationSlider.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

    // Connect to controller.html
    controllerURL = "http://" + ipText + ":8080/controller.html";
    locationSlider = (WebView) findViewById(R.id.webview);
    locationSliderContainer = (FrameLayout) findViewById(R.id.sliderContainer);
    locationSlider.setBackgroundColor(Color.TRANSPARENT);
    locationSlider.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    locationSlider.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            System.out.println("onReceivedError");
            showConnectDialog("Error while connecting to controller. Connect again.");
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("thumbnail"))
                isMasterConnected = true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            isMasterConnectedTimerTask = null;
            isMasterConnectedTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isMasterConnected == false)
                        showConnectDialog("Master is not loaded in the browser. Connect again.");
                }
            };
            isMasterConnectedTimer.schedule(isMasterConnectedTimerTask, 6000);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.contains(controllerURL)) {
                drag.setVisibility(View.VISIBLE);
                playPause.setVisibility(View.VISIBLE);
                loadPreferences();
            }
            super.onPageFinished(view, url);
        }
    });
    try {
        locationSlider.loadUrl(controllerURL);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set JavaScript Interface
    locationSlider.addJavascriptInterface(this, "androidObject");
    WebSettings webSettings = locationSlider.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Set the play-pause button
    playPause = (ImageButton) findViewById(R.id.playPauseButton);
    playPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            socket.emit("handlePlayPauseServer");
        }
    });
    socket.emit("setControllerPlayButton");

    // Set the drag button
    drag = (ImageButton) findViewById(R.id.drag);
    drag.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                dragYDiffBetweenFingerAndSliderTop = locationSliderContainer.getY() - event.getRawY();
                dragYDiffBetweenFingerAndPlayPauseTop = playPause.getY() - event.getRawY();
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                // Move the slider based on current finger location
                float newSliderY = event.getRawY() + dragYDiffBetweenFingerAndSliderTop;
                float newPlayPauseY = event.getRawY() + dragYDiffBetweenFingerAndPlayPauseTop;
                if (newSliderY > minLocationSliderContainerY && newSliderY < maxLocationSliderContainerY) {
                    locationSliderContainer.setY(newSliderY);
                    playPause.setY(newPlayPauseY);
                }
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getEventTime() - event.getDownTime() <= tapTimeout) {
                    // Tap is detected, toggle the slider
                    System.out.println("onTap");
                    runOnUiThread(new Runnable() {
                        public void run() {
                            toggleSlider();
                        }
                    });
                } else {
                    // Not a tap gesture, slide up or down based on the slider's current position
                    if (locationSliderContainer.getY() > midLocationSliderContainerY)
                        slideDown();
                    else
                        slideUp();
                }
            }
            return true;
        }
    });

    // Set the Google map
    setUpMapIfNeeded();
}

From source file:nl.phanos.liteliveresultsclient.gui.ResultsWindows.java

public void setSerieResults(ResultFile resultFile) {
    //updateChromeCast();
    this.resultFile = resultFile;
    System.out.println("photo:" + resultFile.Photo);
    showPhoto();/*from  w w w  .ja v  a2  s  . com*/
    SerieLabel.setText(
            resultFile.BelongsTo.onderdeel + " Serie " + resultFile.BelongsTo.serie + " " + resultFile.wind);
    currentDisplayDate = resultFile.BelongsTo.uploadDate;
    ((DefaultTableModel) jTable1.getModel()).setRowCount(0);
    for (ResultFileEntry entry : resultFile.atleten.values()) {
        ((DefaultTableModel) jTable1.getModel())
                .addRow(new Object[] { entry.plaats, entry.atleet.naam, entry.tijdMooi() });
    }
    ((DefaultTableModel) jTable1.getModel()).addRow(new Object[] { jTable1.getRowCount() + 1, "", "" });
    //if (isCellVisible(jTable1, jTable1.getRowCount() - 1, jTable1.getColumnCount())) {
    Timer timer = new Timer();
    tt = new TimerTask() {

        @Override
        public void run() {
            jTable1.scrollRectToVisible(jTable1.getCellRect(currentRow, jTable1.getColumnCount(), true));
            //System.out.println("currentRow:"+currentRow);
            if (currentRow < jTable1.getRowCount()) {
                currentRow++;
            } else {
                currentRow = 0;
                //tt.cancel();
            }
        }
    };
    timer.schedule(tt, 0, 3000);
    //}
    //
}

From source file:de.madvertise.android.sdk.MadView.java

/**
 * Handles the refresh timer//from   ww  w.  j  a va2s  .co m
 * @param starting
 */
private void refreshAdTimer(boolean starting) {
    synchronized (this) {
        if (starting) {
            if (adTimer == null) {
                adTimer = new Timer();
                adTimer.schedule(new TimerTask() {
                    public void run() {
                        MadUtil.logMessage(null, Log.DEBUG, "Refreshing ad ...");
                        requestNewAd();
                    }
                }, (long) 0, (long) secondsToRefreshAd * 1000);
            }
        } else {
            if (adTimer != null) {
                MadUtil.logMessage(null, Log.DEBUG, "Stopping refresh timer ...");
                adTimer.cancel();
                adTimer = null;
            }
        }
    }
}

From source file:com.irccloud.android.Notifications.java

public synchronized void showNotifications(String ticker) {
    if (ticker != null)
        mTicker = ColorFormatter.emojify(ticker);

    if (mNotificationTimerTask == null) {
        try {//from  ww  w .  j  a v a2 s.  c  o m
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    mNotificationTimerTask = null;
                    showMessageNotifications(mTicker);
                    showOtherNotifications();
                    mTicker = null;
                    IRCCloudApplication.getInstance().getApplicationContext()
                            .sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
                    updateTeslaUnreadCount();
                }

                @Override
                public boolean cancel() {
                    mNotificationTimerTask = null;
                    return super.cancel();
                }
            };
            mNotificationTimer.schedule(task, 5000);
            mNotificationTimerTask = task;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestService.java

/**
 * Start rss change timer.//  w w  w .  j  a v a  2s  .  co m
 */
public void startRssChangeTimer() {
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            checkForUpdates(bioportalRssFeedClient.getBioportalRssFeed());
        }

    }, 0, ONE_MINUTE * this.cacheUpdatePeriod);
}

From source file:com.thebuzzmedia.exiftool.ExifTool.java

private void ensureProcessRunning() {
    if (process == null || process.isClosed()) {
        synchronized (this) {
            if (process == null || process.isClosed()) {
                log.debug(/*from w  ww . ja  v a 2 s  . com*/
                        "Starting daemon ExifTool process and creating read/write streams (this only happens once)...");
                process = ExifProcess.startup(exifCmd);
            }
        }
    }
    if (processCleanupDelay > 0) {
        synchronized (this) {
            if (currentCleanupTask != null) {
                currentCleanupTask.cancel();
                currentCleanupTask = null;
            }
            currentCleanupTask = new TimerTask() {
                @Override
                public void run() {
                    log.info("Auto cleanup task running...");
                    process.close();
                }
            };
            cleanupTimer.schedule(currentCleanupTask, processCleanupDelay);
        }
    }
}