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.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*from w w w.  j a v a 2 s  .c om*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:edu.uci.ics.hyracks.control.nc.NodeControllerService.java

public NodeControllerService(NCConfig ncConfig) throws Exception {
    this.ncConfig = ncConfig;
    id = ncConfig.nodeId;/* w  ww.  j  a v a  2s  .  co m*/
    NodeControllerIPCI ipci = new NodeControllerIPCI();
    ipc = new IPCSystem(new InetSocketAddress(ncConfig.clusterNetIPAddress, ncConfig.clusterNetPort), ipci,
            new CCNCFunctions.SerializerDeserializer());

    this.ctx = new RootHyracksContext(this, new IOManager(getDevices(ncConfig.ioDevices)));
    if (id == null) {
        throw new Exception("id not set");
    }
    partitionManager = new PartitionManager(this);
    netManager = new NetworkManager(ncConfig.dataIPAddress, ncConfig.dataPort, partitionManager,
            ncConfig.nNetThreads, ncConfig.nNetBuffers, ncConfig.dataPublicIPAddress, ncConfig.dataPublicPort);

    lccm = new LifeCycleComponentManager();
    queue = new WorkQueue();
    jobletMap = new Hashtable<JobId, Joblet>();
    timer = new Timer(true);
    serverCtx = new ServerContext(ServerContext.ServerType.NODE_CONTROLLER,
            new File(new File(NodeControllerService.class.getName()), id));
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    threadMXBean = ManagementFactory.getThreadMXBean();
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    osMXBean = ManagementFactory.getOperatingSystemMXBean();
    registrationPending = true;
    getNodeControllerInfosAcceptor = new MutableObject<FutureValue<Map<String, NodeControllerInfo>>>();
    memoryManager = new MemoryManager(
            (long) (memoryMXBean.getHeapMemoryUsage().getMax() * MEMORY_FUDGE_FACTOR));
    ioCounter = new IOCounterFactory().getIOCounter();
}

From source file:io.fabric8.mq.autoscaler.MQAutoScaler.java

public void start() throws Exception {
    if (started.compareAndSet(false, true)) {
        setBrokerSelector("container=java,name=" + getBrokerName() + ",group=" + getGroupName());
        setConsumerSelector("container=java,name=fabric8MQConsumer,group=fabric8MQConsumer");
        setProducerSelector("container=java,name=fabric8MQProducer,group=fabric8MQProducer");
        MQAutoScalerObjectName = new ObjectName(DEFAULT_DOMAIN, "type", "mq-autoscaler");
        JMXUtils.registerMBean(this, MQAutoScalerObjectName);

        kubernetes = new DefaultKubernetesClient();
        clients = new JolokiaClients(kubernetes);

        timer = new Timer("MQAutoScaler timer");
        startTimerTask();/*from  ww w.ja v  a  2  s  .  c om*/
        LOG.info("MQAutoScaler started, using Kubernetes master " + kubernetes.getMasterUrl());
    }
}

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:com.lfv.lanzius.application.Controller.java

private Controller() {
    log = LogFactory.getLog(getClass());
    log.info(Config.VERSION + "\n");
    timer = new Timer("Scontroller");
    radioAcquiredChannelsList = new LinkedList<ClientChannel>();
    radioUnacquiredChannelsList = new LinkedList<ClientChannel>();
    radioDecodingList = new LinkedList<AudioDecoder>();
    volumeClipList = new LinkedList<VolumeAdjustable>();
    volumeRadioList = new LinkedList<VolumeAdjustable>();
}

From source file:io.logspace.hq.core.solr.agent.SolrAgentService.java

@Override
@PostConstruct/*from   ww  w. jav a2s.  com*/
public void initialize() {
    new Timer(true).schedule(new RefreshAgentDescriptionCacheTask(), AGENT_DESCRIPTION_REFRESH_INTERVAL,
            AGENT_DESCRIPTION_REFRESH_INTERVAL);
}

From source file:hudson.plugins.blazemeter.PerformanceBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener) throws InterruptedException, IOException {

    if (!validateTestId(listener)) {
        run.setResult(Result.FAILURE);
        return;//  ww  w .java  2  s  . c om
    }

    BlazemeterCredentialsBAImpl credentials = Utils.findCredentials(credentialsId, CredentialsScope.GLOBAL);
    boolean isValidCredentials = !StringUtils.isBlank(credentialsId) && validateCredentials(credentials);
    if (!isValidCredentials) {
        listener.error(BzmJobNotifier.formatMessage("Can not start build: Invalid credentials=" + credentialsId
                + "... is deprecated or absent in credentials store."));
        run.setResult(Result.NOT_BUILT);
        return;
    }

    String serverUrlConfig = BlazeMeterPerformanceBuilderDescriptor.getDescriptor().getBlazeMeterURL();
    String jobName = run.getFullDisplayName();
    VirtualChannel channel = launcher.getChannel();

    final long reportLinkId = System.currentTimeMillis();
    EnvVars envVars = run.getEnvironment(listener);

    BzmBuild bzmBuild = new BzmBuild(this, credentials.getUsername(), credentials.getPassword().getPlainText(),
            jobName, run.getId(),
            StringUtils.isBlank(serverUrlConfig) ? Constants.A_BLAZEMETER_COM : serverUrlConfig, envVars,
            workspace, listener, ProxyConfiguration.load(), !(channel instanceof LocalChannel),
            envVars.expand(reportLinkName), reportLinkId);

    ReportUrlTask reportUrlTask = new ReportUrlTask(run, jobName, channel, reportLinkId);

    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(reportUrlTask, 20 * 1000, 10 * 1000);
    try {
        Result result = channel.call(bzmBuild);
        run.setResult(result);
    } catch (InterruptedException e) {
        LOGGER.warning("Build has been aborted");
        // start new task for wait Slave
        InterruptListenerTask interrupt = new InterruptListenerTask(run, jobName, channel);
        interrupt.start();
        interrupt.join();
        run.setResult(Result.ABORTED);
    } catch (Exception e) {
        listener.getLogger().println(BzmJobNotifier.formatMessage("Failure with exception: " + e.getMessage()));
        e.printStackTrace(listener.getLogger());
        run.setResult(Result.FAILURE);
    } finally {
        reportUrlTask.cancel();
        timer.cancel();
        timer.purge();
    }
}

From source file:fi.helsinki.opintoni.config.SAMLSecurityConfiguration.java

@Bean
@Qualifier("idp-ssocircle")
public ExtendedMetadataDelegate idpMetadata() throws MetadataProviderException {
    HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(new Timer("idpMetadataRefreshTimer"),
            new HttpClient(), appConfiguration.get("saml.idp.metadataUrl"));
    httpMetadataProvider.setParserPool(parserPool());

    ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider,
            idpExtendedMetadata());//from  w w w.j a  v a  2  s.  c om
    extendedMetadataDelegate.setMetadataTrustCheck(true);
    extendedMetadataDelegate.setMetadataRequireSignature(true);
    return extendedMetadataDelegate;
}

From source file:org.ambientdynamix.core.HomeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    // Set our static reference
    activity = this;
    setContentView(R.layout.home_tab);/*  w  w  w.  j a  v  a2  s. c  om*/

    updateCheck();

    points = new HashSet<>();
    mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_TOKEN);

    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map_main));

    // Check if we were successful in obtaining the map.
    if (mMap == null) {
        // check if google play service in the device is not available or out-dated.
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        // nothing anymore, cuz android will take care of the rest (to remind user to update google play service).
    }

    // Construct the data source
    sensorMeasurements = new ArrayList<>();
    // Create the adapter to convert the array to views
    sensorMeasurementAdapter = new SensorMeasurementAdapter(this, sensorMeasurements);
    // Attach the adapter to a ListView
    final TwoWayView listView = (TwoWayView) findViewById(R.id.lvItems);
    listView.setOrientation(TwoWayView.Orientation.VERTICAL);
    listView.setPadding(0, 0, 0, 0);
    listView.setItemMargin(0);
    listView.setAdapter(sensorMeasurementAdapter);

    //Disable for now
    final Intent activityRecognitionIntent = new Intent(this, ActivityRecognitionService.class);
    activityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 0,
            activityRecognitionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    pendingSendButton = (Button) findViewById(R.id.send_pending_now);
    pendingSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncReportOnServerTask().execute();
            try {
                final JSONObject props = new JSONObject();
                props.put("count", DynamixService.getDataStorageSize());
                //mMixpanel.track("send-stored-readings", props);
            } catch (JSONException ignore) {
            }

        }
    });

    // Setup an state refresh timer, which periodically updates application
    // state in the appList
    final Timer refresher = new Timer(true);
    final TimerTask t = new TimerTask() {
        @Override
        public void run() {

            refreshData();
        }
    };
    refresher.scheduleAtFixedRate(t, 0, 5000);

    phoneIdTv = (TextView) this.findViewById(R.id.deviceId_label);

    expDescriptionTv = (TextView) this.findViewById(R.id.experiment_description);

    if (mMap.getMap() != null) {
        mMap.getMap().setMyLocationEnabled(true);
        mMap.getMap().getUiSettings().setAllGesturesEnabled(false);
        mMap.getMap().getUiSettings().setMyLocationButtonEnabled(false);
    }
}

From source file:eu.project.ttc.engines.morpho.CompostAE.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    SubTaskObserver observer = observerResource.getTaskObserver(TASK_NAME);
    observer.setTotalTaskWork(termIndexResource.getTermIndex().getWords().size());
    LOGGER.info("Starting morphologyical compound detection for TermIndex {}",
            this.termIndexResource.getTermIndex().getName());
    LOGGER.debug(this.toString());
    wrMeasure = termIndexResource.getTermIndex().getWRMeasure();
    swtLemmaIndex = termIndexResource.getTermIndex().getCustomIndex(TermIndexes.SINGLE_WORD_LEMMA);
    buildCompostIndex();//from   w ww .  j  ava 2s  .c o  m

    final MutableLong cnt = new MutableLong(0);

    Timer progressLoggerTimer = new Timer("Morphosyntactic splitter AE");
    progressLoggerTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            int total = termIndexResource.getTermIndex().getWords().size();
            CompostAE.LOGGER.info("Progress: {}% ({} on {})",
                    String.format("%.2f", ((float) cnt.longValue() * 100) / total), cnt.longValue(), total);
        }
    }, 5000l, 5000l);

    int observingStep = 100;
    for (Term swt : termIndexResource.getTermIndex().getTerms()) {
        if (!swt.isSingleWord())
            continue;
        cnt.increment();
        if (cnt.longValue() % observingStep == 0) {
            observer.work(observingStep);
        }

        /*
         * Do not do native morphology splitting 
         * if a composition already exists.
         */
        Word word = swt.getWords().get(0).getWord();
        if (word.isCompound())
            continue;

        Map<Segmentation, Double> scores = computeScores(word.getLemma());
        if (scores.size() > 0) {

            List<Segmentation> segmentations = Lists.newArrayList(scores.keySet());

            /*
             *  compare segmentations in a deterministic way.
             */
            segmentations.sort(new Comparator<Segmentation>() {
                @Override
                public int compare(Segmentation o1, Segmentation o2) {
                    int comp = Double.compare(scores.get(o2), scores.get(o1));
                    if (comp != 0)
                        return comp;
                    comp = Integer.compare(o1.getSegments().size(), o2.getSegments().size());
                    if (comp != 0)
                        return comp;
                    for (int i = 0; i < o1.getSegments().size(); i++) {
                        comp = Integer.compare(o2.getSegments().get(i).getEnd(),
                                o1.getSegments().get(i).getEnd());
                        if (comp != 0)
                            return comp;
                    }
                    return 0;
                }
            });

            Segmentation bestSegmentation = segmentations.get(0);

            // build the word component from segmentation
            WordBuilder builder = new WordBuilder(word);

            for (Segment seg : bestSegmentation.getSegments()) {
                String lemma = segmentLemmaCache.getUnchecked(seg.getLemma());
                builder.addComponent(seg.getBegin(), seg.getEnd(), lemma);
                if (seg.isNeoclassical())
                    builder.setCompoundType(CompoundType.NEOCLASSICAL);
                else
                    builder.setCompoundType(CompoundType.NATIVE);
            }
            builder.create();

            // log the word composition
            if (LOGGER.isTraceEnabled()) {
                List<String> componentStrings = Lists.newArrayList();
                for (Component component : word.getComponents())
                    componentStrings.add(component.toString());
                LOGGER.trace("{} [{}]", word.getLemma(), Joiner.on(' ').join(componentStrings));
            }
        }
    }

    //finalize
    progressLoggerTimer.cancel();

    LOGGER.debug("segment score cache size: {}", segmentScoreEntries.size());
    LOGGER.debug("segment score hit count: " + segmentScoreEntries.stats().hitCount());
    LOGGER.debug("segment score hit rate: " + segmentScoreEntries.stats().hitRate());
    LOGGER.debug("segment score eviction count: " + segmentScoreEntries.stats().evictionCount());
    termIndexResource.getTermIndex().dropCustomIndex(TermIndexes.SINGLE_WORD_LEMMA);
    segmentScoreEntries.invalidateAll();
    segmentLemmaCache.invalidateAll();
}