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.sf.taverna.t2.reference.ReferenceServiceTest.java

@Test
/**/*  w ww. j a va 2s.  com*/
 * Test multiple concurrent read / write cycles to the database, producing
 * some rather informal profiling information at the end.
 */
public void testSaturatedReadWriteCycle() throws MalformedURLException {
    int concurrentThreads = 5;
    final int jobsPerThread = 200;
    int joinPoints = 5;
    final URL testUrl = new URL("http://www.ebi.ac.uk/~tmo/patterns.xml");
    ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
            "referenceServiceTestContext.xml");
    //      ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
    //      "inMemoryReferenceServiceTestContext.xml");
    final ReferenceService rs = (ReferenceService) context.getBean("t2reference.service.referenceService");
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private int lastCount = getCount();
        private long lastTime = System.currentTimeMillis();

        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            long interval = currentTime - lastTime;
            lastTime = currentTime;
            int newCount = getCount();
            long jobsProcessed = (long) (newCount - lastCount);
            lastCount = newCount;
            if (interval == 0) {
                System.out.println("(infinity) " + jobsProcessed);
            } else {
                System.out.println((int) (jobsProcessed * 1000 / interval));
            }
        }
    }, 1000, 1000);
    long testStartTime = System.currentTimeMillis();
    for (int i = 0; i < joinPoints; i++) {
        Thread[] threads = new Thread[concurrentThreads];
        for (int j = 0; j < concurrentThreads; j++) {
            threads[j] = new Thread() {
                @Override
                public void run() {
                    for (int k = 0; k < jobsPerThread; k++) {
                        try {
                            //                        T2Reference ref = rs.register("test", 0, true,
                            //                              dummyContext);
                            T2Reference ref = rs.register(testUrl, 0, true, dummyContext);
                            @SuppressWarnings("unused")
                            ReferenceSet refSet = (ReferenceSet) rs.resolveIdentifier(ref, null, dummyContext);
                            incrementRequestsProcessed();
                        } catch (ReferenceServiceException rse) {
                            System.out.println(rse);
                        }
                    }
                }
            };
            threads[j].start();
        }
        for (int j = 0; j < concurrentThreads; j++) {
            try {
                threads[j].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    timer.cancel();
    System.out.println("Test completed, using " + concurrentThreads + " threads, " + getCount() + " at "
            + (long) ((getCount() * 1000) / (System.currentTimeMillis() - testStartTime))
            + " jobs per second averaged over test run");
    System.out.println((System.currentTimeMillis() - testStartTime));
    System.out.println((System.currentTimeMillis() - testStartTime) / (float) (jobsPerThread * joinPoints));
}

From source file:org.spee.sbweb.controller.SBWebController.java

@Override
public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
    System.out.println(/*w ww  .  j av a  2  s  .  c  o m*/
            "SBWebControler.java - ServletContext: images - " + this.servletContext.getRealPath("/images"));
    System.out.println("SBWebControler.java - ServletContext: root - " + this.servletContext.getRealPath("/"));

    Timer t = new Timer();
    CronJobs mTask = new CronJobs();

    t.scheduleAtFixedRate(mTask, 0, TIME_TO_CHECK_IMAGE_FOLDER);

}

From source file:org.apache.hcatalog.hcatmix.load.HCatMapper.java

@Override
public void map(LongWritable longWritable, Text text, OutputCollector<LongWritable, IntervalResult> collector,
        final Reporter reporter) throws IOException {
    LOG.info(MessageFormat.format("Input: {0}={1}", longWritable, text));
    final List<Future<SortedMap<Long, IntervalResult>>> futures = new ArrayList<Future<SortedMap<Long, IntervalResult>>>();

    // Initialize tasks
    List<org.apache.hcatalog.hcatmix.load.tasks.Task> tasks;
    try {//from  w w  w.  ja v  a 2s .c  o m
        tasks = initializeTasks(jobConf);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    ThreadCreatorTimer createNewThreads = new ThreadCreatorTimer(new TimeKeeper(timeKeeper), tasks,
            threadIncrementCount, futures, reporter);

    // Create timer thread to automatically keep on increasing threads at fixed interval
    Timer newThreadCreator = new Timer(true);
    newThreadCreator.scheduleAtFixedRate(createNewThreads, 0, threadIncrementIntervalInMillis);

    // Sleep and let the tasks get expired
    long remainingTime = timeKeeper.getRemainingTimeIncludingBuffer();
    final long sleepPeriod = 2000;
    for (long i = remainingTime; i > 0; i = i - sleepPeriod) {
        try {
            Thread.sleep(sleepPeriod);
            reporter.progress();
        } catch (InterruptedException e) {
            LOG.error("Got interrupted while sleeping for timer thread to finish");
        }
    }

    newThreadCreator.cancel();
    LOG.info("Time is over, will collect the futures now. Total number of threads: " + futures.size());
    SortedMap<Long, IntervalResult> stopWatchAggregatedTimeSeries = new TreeMap<Long, IntervalResult>();

    // Merge the corresponding time interval results received from all the threads for each time interval
    for (TaskExecutor taskExecutor : createNewThreads.getTaskExecutors()) {
        try {
            SortedMap<Long, IntervalResult> threadTimeSeries = taskExecutor.getTimeSeriesResult();
            for (Map.Entry<Long, IntervalResult> entry : threadTimeSeries.entrySet()) {
                Long timeStamp = entry.getKey();
                IntervalResult intervalResult = entry.getValue();

                if (stopWatchAggregatedTimeSeries.containsKey(timeStamp)) {
                    stopWatchAggregatedTimeSeries.get(timeStamp).addIntervalResult(intervalResult);
                } else {
                    stopWatchAggregatedTimeSeries.put(timeStamp, intervalResult);
                }
                LOG.info(MessageFormat.format("{0}: Added {1} stopwatches. Current stopwatch number: {2}",
                        timeStamp, intervalResult.getStopWatchList().size(),
                        stopWatchAggregatedTimeSeries.get(timeStamp).getStopWatchList().size()));
            }
        } catch (Exception e) {
            LOG.error("Error while getting thread results", e);
        }
    }

    // Output the consolidated result for this map along with the number of threads against time
    LOG.info("Collected all the statistics for #threads: " + createNewThreads.getThreadCount());
    SortedMap<Long, Integer> threadCountTimeSeries = createNewThreads.getThreadCountTimeSeries();
    int threadCount = 0;
    for (Map.Entry<Long, IntervalResult> entry : stopWatchAggregatedTimeSeries.entrySet()) {
        long timeStamp = entry.getKey();
        IntervalResult intervalResult = entry.getValue();
        if (threadCountTimeSeries.containsKey(timeStamp)) {
            threadCount = threadCountTimeSeries.get(timeStamp);
        }
        intervalResult.setThreadCount(threadCount);
        collector.collect(new LongWritable(timeStamp), intervalResult);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.semantic.SimpleSemanticFactory.java

/**
 * Creates temporary files for ontology document storing and
 * sets the timer to run the transformation process regularly.
 *///from  w ww .  j  a  v  a 2  s  .  co m
public void init() {
    try {
        ontologyFile = File.createTempFile("ontology_", ".rdf.tmp");
        ontologyFile.deleteOnExit();
    } catch (IOException e) {
        log.error("Could not create the temporary rdf/xml file to store the ontology!", e);
    }

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TransformTask(), delay, interval);
}

From source file:ezbake.frack.common.workers.WarehausBatchWorker.java

/**
 * Initializes the warehaus batch worker with required variables.
 * @param props contains ezbake properties.
 *///from  ww w . j  av  a  2  s.c  o  m
@Override
public void initialize(Properties props) {
    EzProperties ezProps = new EzProperties(props, true);
    this.maxQueueSize = ezProps.getInteger(BATCH_SIZE_KEY, 50);
    this.pool = new ThriftClientPool(props);
    this.warehausSecurityId = pool.getSecurityId(WarehausServiceConstants.SERVICE_NAME);
    this.putRequest = new PutRequest();
    this.securityClient = new EzbakeSecurityClient(props);
    objects = Lists.newArrayList();
    visibilities = Lists.newArrayList();
    Timer batchWriterTimer = new Timer();
    batchWriterTimer.scheduleAtFixedRate(new WarehausBatchTask(), 0,
            Long.valueOf(props.getProperty("warehouse.batch.timeout", String.valueOf(15000))));
    logger.info("Creating Batch Writer with max queue size of: {}", maxQueueSize);
}

From source file:org.commonjava.indy.revisions.RevisionsManager.java

@PostConstruct
public void setup() {
    try {//from ww w  . j av  a 2s  .  c  o  m
        final File dataDir = dataFileManager.getDetachedDataBasedir();
        final File gitignore = new File(dataDir, ".gitignore");

        dataDir.mkdirs();
        FileUtils.write(gitignore, join(DATA_DIR_GITIGNORES, "\n"));

        final GitConfig dataConf = new GitConfig(dataDir, revisionsConfig.getDataUpstreamUrl(), true)
                .setRemoteBranchName(revisionsConfig.getBranchName())
                .setUserEmail(revisionsConfig.getUserEmail());

        dataFileGit = new GitManager(dataConf);

        // we need a TimerTask that will commit modifications periodically
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    int committed = commitDataUpdates();
                    if (committed > 0) {
                        logger.info("Commit and push data updates, size: " + committed);
                        pushDataUpdates();
                    }
                } catch (GitSubsystemException e) {
                    logger.warn("Failed to push data updates", e);
                }
            }
        }, 1000, 60 * 1000); // every 1 min
    } catch (GitSubsystemException | IOException e) {
        throw new IllegalStateException("Failed to start revisions manager: " + e.getMessage(), e);
    } finally {
    }
}

From source file:gridool.metrics.GridNodeMetricsProvider.java

void start() throws GridException {
    registerMBeans(localMetrics);// ww  w  . java 2 s. c o  m

    MetricsCollector collectorTask = new MetricsCollector(localMetrics, metricsHistories);
    Timer timer = new Timer("gridool#MetricsCollector", true);
    timer.scheduleAtFixedRate(collectorTask, 1000, collectInterval);
    this.metricsCollector = collectorTask;
    this.timer = timer;
}

From source file:cz.cvut.fel.webrtc.handlers.WebHandler.java

public WebHandler() {
    super();/*from  ww  w .j a  va  2 s .c  o m*/
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            Calendar currentDate = Calendar.getInstance();

            for (WebUser user : registry.getAll()) {
                Calendar ping = user.getLastPing();
                ping.add(Calendar.SECOND, 40);

                if (ping.before(currentDate)) {
                    try {
                        log.info("{} is unreachable.", user.getName());
                        leaveRoom(user);
                    } catch (Exception e) {
                    }
                }
            }
        }

    };

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 30000, 30000);
}

From source file:com.easibeacon.examples.shop.MainActivity.java

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

    _barSearchBeacons = (ProgressBar) findViewById(R.id.barSearchBeacons);
    _txtState = (TextView) findViewById(R.id.txtState);

    ibp = IBeaconProtocol.getInstance(this);
    ibp.setListener(this);

    TimerTask searchIbeaconTask = new TimerTask() {
        @Override/*  w  w  w. j a v a 2s  . c  o  m*/
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    scanBeacons();
                }
            });
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(searchIbeaconTask, 1000, 2000);

}

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;/*  w w w. j av a2 s  .  com*/
    }

    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();
    }
}