Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

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

Prototype

public Timer(String name) 

Source Link

Document

Creates a new timer whose associated thread has the specified name.

Usage

From source file:com.moilioncircle.redis.replicator.RedisSocketReplicator.java

/**
 * PSYNC/* www  .  j  a v  a 2 s .c om*/
 *
 * @throws IOException when read timeout or connect timeout
 */
@Override
public void open() throws IOException {
    worker.start();
    for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) {
        try {
            connect();

            if (configuration.getAuthPassword() != null)
                auth(configuration.getAuthPassword());

            sendSlavePort();

            sendSlaveIp();

            sendSlaveCapa();

            //reset retries
            i = 0;

            logger.info("PSYNC " + configuration.getMasterRunId() + " "
                    + String.valueOf(configuration.getOffset()));
            send("PSYNC".getBytes(), configuration.getMasterRunId().getBytes(),
                    String.valueOf(configuration.getOffset()).getBytes());
            final String reply = (String) reply();

            SyncMode syncMode = trySync(reply);
            //bug fix.
            if (syncMode == SyncMode.PSYNC && connected.get()) {
                //heart beat send REPLCONF ACK ${slave offset}
                synchronized (this) {
                    heartBeat = new Timer("heart beat");
                    //bug fix. in this point closed by other thread. multi-thread issue
                    heartBeat.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                send("REPLCONF".getBytes(), "ACK".getBytes(),
                                        String.valueOf(configuration.getOffset()).getBytes());
                            } catch (IOException e) {
                                //NOP
                            }
                        }
                    }, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod());
                    logger.info("heart beat started.");
                }
            }
            //sync command
            while (connected.get()) {
                Object obj = replyParser.parse(new OffsetHandler() {
                    @Override
                    public void handle(long len) {
                        configuration.addOffset(len);
                    }
                });
                //command
                if (obj instanceof Object[]) {
                    if (configuration.isVerbose() && logger.isDebugEnabled())
                        logger.debug(Arrays.deepToString((Object[]) obj));

                    Object[] command = (Object[]) obj;
                    CommandName cmdName = CommandName.name((String) command[0]);
                    Object[] params = new Object[command.length - 1];
                    System.arraycopy(command, 1, params, 0, params.length);

                    final CommandParser<? extends Command> operations;
                    //if command do not register. ignore
                    if ((operations = commands.get(cmdName)) == null)
                        continue;

                    //do command replyParser
                    Command parsedCommand = operations.parse(cmdName, params);

                    //submit event
                    this.submitEvent(parsedCommand);
                } else {
                    if (logger.isInfoEnabled())
                        logger.info("Redis reply:" + obj);
                }
            }
            //connected = false
            break;
        } catch (/*bug fix*/IOException | InterruptedException e) {
            //close socket manual
            if (!connected.get()) {
                break;
            }
            logger.error("socket error", e);
            //connect refused
            //connect timeout
            //read timeout
            //connect abort
            //server disconnect connection EOFException
            close();
            //retry psync in next loop.
            logger.info("reconnect to redis-server. retry times:" + (i + 1));
            try {
                Thread.sleep(configuration.getRetryTimeInterval());
            } catch (InterruptedException e1) {
                //non interrupted
                logger.error("error", e1);
            }
        }
    }
    //
    if (worker != null && !worker.isClosed())
        worker.close();
}

From source file:com.microsoft.tfs.client.eclipse.ui.egit.importwizard.CrossCollectionRepositorySelectControl.java

public CrossCollectionRepositorySelectControl(final Composite parent, final int style,
        final SourceControlCapabilityFlags sourceControlCapabilityFlags) {
    super(parent, style);

    final GridLayout layout = new GridLayout();
    layout.marginWidth = 0;/*from   w  w w  .j av a2s .  c  om*/
    layout.marginHeight = 0;
    layout.horizontalSpacing = getHorizontalSpacing();
    layout.verticalSpacing = 0;
    setLayout(layout);

    // Create timer for filtering the list
    filterTimer = new Timer(false);

    // Create the filter text box
    filterBox = new Text(this, SWT.BORDER);
    filterBox.setMessage(Messages.getString("CrossCollectionRepositorySelectControl.FilterHintText")); //$NON-NLS-1$
    filterBox.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(final ModifyEvent e) {
            startTimer();
        }
    });
    GridDataBuilder.newInstance().hGrab().hFill().applyTo(filterBox);

    table = new CrossCollectionRepositoryTable(this, SWT.NONE);
    table.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(final SelectionChangedEvent event) {
            onSelectionChanged(true);
        }
    });
    GridDataBuilder.newInstance().grab().hHint(getVerticalSpacing() * 30).vIndent(getVerticalSpacing()).fill()
            .applyTo(table);

    final Label parentDirectoryLabel = SWTUtil.createLabel(this,
            Messages.getString("CrossCollectionRepositorySelectControl.ParentDirectoryLabelText")); //$NON-NLS-1$
    GridDataBuilder.newInstance().hGrab().vIndent(getVerticalSpacing()).hFill().applyTo(parentDirectoryLabel);

    final Composite container = new Composite(this, SWT.NONE);
    final GridLayout layout2 = SWTUtil.gridLayout(container, 2, false, 0, 0);
    layout2.marginWidth = 0;
    layout2.marginHeight = 0;
    layout2.horizontalSpacing = getHorizontalSpacing();
    layout2.verticalSpacing = getVerticalSpacing();
    container.setLayout(layout2);

    parentDirectoryBox = new Text(container, SWT.BORDER);
    parentDirectoryBox.setText(getDefaultGitRootFolder());
    GridDataBuilder.newInstance().hGrab().hFill().applyTo(parentDirectoryBox);
    parentDirectoryBox.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(final ModifyEvent e) {
            onSelectionChanged(false);
        }
    });

    browseButton = SWTUtil.createButton(container,
            Messages.getString("CrossCollectionRepositorySelectControl.BrowseButtonText")); //$NON-NLS-1$
    browseButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            parentDirectoryBox.setText(browse(parentDirectoryBox.getText()));
        }
    });
    GridDataBuilder.newInstance().hGrab().hFill().applyTo(container);

    final Label folderNameLabel = SWTUtil.createLabel(this,
            Messages.getString("CrossCollectionRepositorySelectControl.RepositoryFolderLabelText")); //$NON-NLS-1$
    GridDataBuilder.newInstance().hGrab().vIndent(getVerticalSpacing()).hFill().applyTo(folderNameLabel);

    folderNameBox = new Text(this, SWT.BORDER);
    GridDataBuilder.newInstance().hGrab().hFill().applyTo(folderNameBox);
    folderNameBox.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(final ModifyEvent e) {
            onSelectionChanged(false);
        }
    });
}

From source file:com.haulmont.cuba.core.app.ServerInfo.java

@Override
public void applicationStarted() {
    if (!globalConfig.getTestMode()) {
        infoUpdateTimer = new Timer(true);
        infoUpdateTimer.schedule(new TimerTask() {
            @Override/*from  w w  w.  j a v  a 2  s.co  m*/
            public void run() {
                Thread.currentThread().setName("ServerInfoTimer");

                if (AppContext.isStarted()) {
                    updateCurrentServer();
                }
            }
        }, 30000, 60000);
    }
}

From source file:heigit.ors.routing.RoutingProfilesUpdater.java

public void start() {
    // parse time of the format: day of the week, time, period
    String strDateTime = m_config.Time;
    String[] splitValues = strDateTime.split(",");
    int dayOfWeek = Integer.valueOf(splitValues[0].trim()) + 1; // Sunday is 1.
    m_updatePeriod = Integer.valueOf(splitValues[2].trim());
    splitValues = splitValues[1].trim().split(":");
    int hours = Integer.valueOf(splitValues[0].trim());
    int minutes = Integer.valueOf(splitValues[1].trim());
    int seconds = Integer.valueOf(splitValues[2].trim());

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
    calendar.set(Calendar.HOUR_OF_DAY, hours);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.SECOND, seconds);

    Date firstUpdateTime = calendar.getTime();

    TimerTask timerTask = new UpdateTask(this);
    m_timer = new Timer(true);
    m_timer.schedule(timerTask, firstUpdateTime, m_updatePeriod);

    m_nextUpdate = firstUpdateTime;/*from  w w  w .j  a va  2 s  .  c  o m*/
    LOGGER.info("Profile updater is started and scheduled at " + firstUpdateTime.toString() + ".");
}

From source file:com.arrow.acs.client.api.ConnectionManager.java

private void restartExpiredTimer() {
    String method = "restartExpiredTimer";

    if (checkExpiredTimer != null) {
        logInfo(method, "cancelling current timer ...");
        checkExpiredTimer.cancel();//from   w w w .j  ava  2  s .  c  o m
        checkExpiredTimer = null;
    }

    logDebug(method, "checkExpiredConnectionIntervalMs: %d", checkExpiredConnectionIntervalMs);
    if (checkExpiredConnectionIntervalMs > 0) {
        checkExpiredTimer = new Timer(true);
        checkExpiredTimer.scheduleAtFixedRate(new TimerTask() {
            AtomicBoolean running = new AtomicBoolean(false);

            @Override
            public void run() {
                if (connectionManager != null) {
                    if (running.compareAndSet(false, true)) {
                        try {
                            logDebug(method, "connectionManager.closeExpiredConnections() ...");
                            connectionManager.closeExpiredConnections();
                        } catch (Throwable t) {
                        }
                    }
                } else {
                    logWarn(method, "connectionManager is not available!");
                }
            }
        }, 0, checkExpiredConnectionIntervalMs);
    } else {
        logWarn(method, "timer is NOT scheduled, checkExpiredConnectionIntervalMs: %d",
                checkExpiredConnectionIntervalMs);
    }
}

From source file:com.zb.app.websocket.server.WebSocketServerHandler.java

@PostConstruct
public void init() {
    // ?/*from   w ww  .  j a v  a 2s .c om*/
    if (timer != null) {
        stop();
    }
    timer = new Timer(false);
    timer.schedule(new CheckTimerTask(), TIMER_START_MILLIS, TIMER_INTERVAL_MILLIS);
    logger.info("CheckTimerTask started; interval={} ms", TIMER_INTERVAL_MILLIS);
}

From source file:com.frostwire.gui.components.slides.MultimediaSlideshowPanel.java

private void setup(List<Slide> slides) {
    this.slides = filter(slides);

    GUIMediator.safeInvokeLater(new Runnable() {
        public void run() {
            List<Slide> slides = MultimediaSlideshowPanel.this.slides;
            try {
                int i = 0;
                for (Slide s : slides) {
                    add(new SlidePanel(s, i), String.valueOf(i));
                    i++;/*from  w  ww  .j a  v a  2s.  c o m*/
                }

                if (container != null && useControls) {
                    container.add(new SlideshowPanelControls(MultimediaSlideshowPanel.this),
                            BorderLayout.PAGE_END);
                }

                if (slides != null && !slides.isEmpty()) {
                    timer = new Timer("SlideShow Timer");
                    timer.schedule(new SlideSwitcher(), slides.get(0).duration);
                }
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
    });
}

From source file:io.seldon.clustering.recommender.jdo.JdoClusterFromReferrer.java

private void startReloadTransientTimer(final int delaySeconds) {
    reloadTimer = new Timer(true);
    int period = 1000 * delaySeconds;
    int delay = 1000 * delaySeconds;

    reloadTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            try {
                logger.info("About to update cluster map for client " + client);
                updateClusterMap();/* w w  w .  j  av a 2s  .co  m*/
                logger.info("Updated cluster map for client " + client);
            } catch (Exception e) {
                logger.error("Caught exception trying to load transient clusters", e);
            } finally {
                JDOFactory.get().cleanupPM();
            }
        }
    }, delay, period);

}

From source file:com.haoocai.jscheduler.core.tracker.ZKTaskTracker.java

private void setNextTimer(ZKTaskTracker zkTaskTracker) {
    Date nextRunTime = task.calcNextRunTime();
    LOG.info("task:{} next run time:{}.", taskID.getName(),
            DateFormatUtils.format(nextRunTime, "yyyy-MM-dd HH:mm:ss"));
    Timer timer = new Timer(taskID.getApp() + "-" + taskID.getName() + "-" + "tracker");
    task.registerNewTracker(zkTaskTracker);
    timer.schedule(zkTaskTracker, nextRunTime);
}

From source file:net.grinder.console.ConsoleFoundationEx.java

/**
 * Constructor. Allows properties to be specified.
 * /*from   w w  w  .j ava 2 s .c  o  m*/
 * @param resources      Console resources
 * @param logger      Logger.
 * @param properties   The properties.
 * @param eventSyncCondition   event synchronization condition.
 * @exception GrinderException   occurs If an error occurs.
 */
public ConsoleFoundationEx(Resources resources, Logger logger, ConsoleProperties properties,
        ConsoleCommunicationSetting consoleCommunicationSetting, Condition eventSyncCondition)
        throws GrinderException {
    m_eventSyncCondition = eventSyncCondition;
    m_container = new DefaultPicoContainer(new Caching());
    m_container.addComponent(logger);
    m_container.addComponent(resources);
    m_container.addComponent(properties);
    m_container.addComponent(StatisticsServicesImplementation.getInstance());
    m_container.addComponent(new StandardTimeAuthority());
    m_container.addComponent(consoleCommunicationSetting);

    m_container.addComponent(SampleModelImplementationEx.class);
    m_container.addComponent(SampleModelViewsImplementation.class);
    m_container.addComponent(ConsoleCommunicationImplementationEx.class);
    m_container.addComponent(DistributionControlImplementation.class);
    m_container.addComponent(ProcessControlImplementation.class);
    m_timer = new Timer(true);
    m_container.addComponent(m_timer);

    //noinspection RedundantArrayCreation
    m_container.addComponent(FileDistributionImplementation.class, FileDistributionImplementation.class,
            new Parameter[] { new ComponentParameter(DistributionControlImplementation.class),
                    new ComponentParameter(ProcessControlImplementation.class),
                    new ConstantParameter(properties.getDistributionDirectory()),
                    new ConstantParameter(properties.getDistributionFileFilterPattern()), });

    m_container.addComponent(DispatchClientCommands.class);
    m_container.addComponent(WireFileDistribution.class);
    m_container.addComponent(WireMessageDispatch.class);
    m_container.addComponent(WireDistributedBarriers.class);
    m_container.addComponent(ErrorQueue.class);

    ErrorQueue errorQueue = m_container.getComponent(ErrorQueue.class);
    errorQueue.setErrorHandler(new ErrorHandlerImplementation(logger));
}