Java Code Examples for java.util.Timer#schedule()

The following examples show how to use java.util.Timer#schedule() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MEMTest.java    From GTTools with MIT License 6 votes vote down vote up
@Test
public void testPss() throws InterruptedException
{
	Timer timer = new Timer();
	
	PssTimerTask task = new PssTimerTask(InstrumentationRegistry.getTargetContext(), android.os.Process.myPid(),
		new DataRefreshListener<Long[]>(){

			@Override
			public void onRefresh(long time, Long[] data) {
				System.out.println(data[0] + "/" + data[1] + "/" + data[2]);
			}});

	timer.schedule(task, 0, 1000);
	Thread.sleep(10000);
}
 
Example 2
Source File: PeakSummaryVisualizerModule.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @see net.sf.mzmine.modules.MZmineModule#setParameters(net.sf.mzmine.data.ParameterSet)
 */
public static void showNewPeakSummaryWindow(PeakListRow row) {
  final PeakSummaryWindow newWindow = new PeakSummaryWindow(row);
  newWindow.setVisible(true);
  newWindow.setLocation(20, 20);
  newWindow.setSize(new Dimension(1000, 600));

  // Hack to show the new window in front of the main window
  Timer timer = new Timer();
  timer.schedule(new TimerTask() {
    public void run() {
      newWindow.toFront();
    }
  }, 200); // msecs
  timer.schedule(new TimerTask() {
    public void run() {
      newWindow.toFront();
    }
  }, 400); // msecs
}
 
Example 3
Source File: TLCServerThread.java    From tlaplus with MIT License 6 votes vote down vote up
public TLCServerThread(TLCWorkerRMI worker, URI aURI, TLCServer tlc, ExecutorService es, IBlockSelector aSelector) {
	super(COUNT++);
	this.executorService = es;
	this.tlcServer = tlc;
	this.selector = aSelector;
	this.uri = aURI;

	// Create Timer early to avoid NPE in handleRemoteWorkerLost (it tries to cancel the timer)
	keepAliveTimer = new Timer("TLCWorker KeepAlive Timer ["
			+ uri.toASCIIString() + "]", true);
	
	// Wrap the TLCWorker with a SmartProxy. A SmartProxy's responsibility
	// is to measure the RTT spend to transfer states back and forth.
	this.worker = new TLCWorkerSmartProxy(worker);

	// Prefix the thread name with a fixed string and a counter.
	// This part is used by the external Munin based statistics software to
	// gather thread contention stats.
	final String i = String.format("%03d", myGetId());
	setName(TLCServer.THREAD_NAME_PREFIX + i + "-[" + uri.toASCIIString() + "]");
	
	// schedule a timer to periodically (60s) check server aliveness
	task = new TLCTimerTask();
	keepAliveTimer.schedule(task, 10000, 60000);
}
 
Example 4
Source File: PVTableModel.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Initialize
 *  @param with_timer With timer to send events?
 */
public PVTableModel(final boolean with_timer)
{
    if (with_timer)
    {
        update_timer = new Timer("PVTableUpdate", true);
        update_timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                performUpdates();
            }
        }, UPDATE_PERIOD_MS, UPDATE_PERIOD_MS);
    }
}
 
Example 5
Source File: CustomTimer.java    From SensorTag-CC2650 with Apache License 2.0 5 votes vote down vote up
public CustomTimer(ProgressBar progressBar, int timeout, CustomTimerCallback cb) {
  mTimeout = timeout;
  mProgressBar = progressBar;
  mTimer = new Timer();
  ProgressTask t = new ProgressTask();
  mTimer.schedule(t, 0, 1000); // One second tick
  mCb = cb;
}
 
Example 6
Source File: TimerTest.java    From java-study with Apache License 2.0 5 votes vote down vote up
public static void timer4() {
  Timer timer = new Timer();
  timer.schedule(new TimerTask() {
    public void run() {
      System.out.println("timer1()  -------设定要指定任务--------");
    }
  }, 2000);// 设定指定的时间time,此处为2000毫秒
}
 
Example 7
Source File: NukeFilterPostHook.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Nukes the specified NukeFilterNukeItem
 *
 * @param nfni item to be nuked
 */
private void nuke(NukeFilterNukeItem nfni, String ircString) {
    //start timer to nuke target in 'delay' seconds
    Timer timer = new Timer();
    NukeFilterNukeTask nfnt = new NukeFilterNukeTask(nfni);
    timer.schedule(nfnt, nfni.getDelay() * 1000);
    //create and unleash NukeFilterEvent
    NukeFilterEvent nfe = new NukeFilterEvent(nfni, ircString);
    GlobalContext.getEventService().publishAsync(nfe);
}
 
Example 8
Source File: LinkResolverHelperFunctions.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * Quick function to setup the daemon to clear domains to keep our memory foot-print low
 */
private static void setupTimer() {
    timer = new Timer(true);
    timer.schedule(new TimerTask() {
        public void run() {
            purgeAnyExpiredDomains();
        }
    }, RECENT_DOMAINS_BACKOFF * 2);
}
 
Example 9
Source File: CamelHotReplacementSetup.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void setupHotDeployment(HotReplacementContext context) {
    Timer timer = new Timer(true);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                context.doScan(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, TWO_SECS, TWO_SECS);
}
 
Example 10
Source File: ConnectionManager.java    From defense-solutions-proofs-of-concept with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a Thread for IO/Parsing/Checking-Making Connections
 * Start another Thread for relaying events
 */
void startMainLoop()
{
	dispatchTimer = new Timer();

	loopTimer = new Timer();

	TimerTask dispatchTask = new TimerTask()
	{
		public void run()
		{
			relayEvents();
			notifyWriteListeners();
		}
	};

	TimerTask loopTask = new TimerTask()
	{
		public void run()
		{
			makeConnections();
			doNetworkIO();
			parseEvents();
			checkServerConnections();
		}
	};

	loopTimer.schedule(loopTask, 0, 200);

	dispatchTimer.schedule(dispatchTask, 0, 200);
}
 
Example 11
Source File: DownstreamHandlerImpl.java    From particle-android with Apache License 2.0 5 votes vote down vote up
private void makeRequest(final DownstreamChannel channel, final HttpURI uri) {
    //LOG.entering(CLASS_NAME, "makeRequest");

    try {
        // Cancel idle timer if running
        stopIdleTimer(channel);
        
        HttpURI requestUri = HttpURI.replaceScheme(uri.getURI(), uri.getScheme().replaceAll("ws", "http"));
        HttpRequest request = HttpRequest.HTTP_REQUEST_FACTORY.createHttpRequest(Method.POST, requestUri, true);
        request.parent = channel;
        channel.outstandingRequests.add(request);

        if (channel.cookie != null) {
            request.setHeader(WebSocketEmulatedHandler.HEADER_COOKIE, channel.cookie);
        }
        
        // Annotate request with sequence number
        request.setHeader(HEADER_SEQUENCE, Long.toString(channel.nextSequence()));
        
        nextHandler.processOpen(request);

        // Note: attemptProxyModeFallback is only set on the channel for http, not https,
        // since attempting detection for HTTPS can also lead to problems if SSL handshake
        // takes more than 5 seconds to complete
        if (!DISABLE_FALLBACK && channel.attemptProxyModeFallback.get()) {
            TimerTask timerTask = new TimerTask() {

                @Override
                public void run() {
                    fallbackToProxyMode(channel);
                }
            };
            Timer t = new Timer("ProxyModeFallback", true);
            t.schedule(timerTask, PROXY_MODE_TIMEOUT_MILLIS);
        }
    } catch (Exception e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        listener.downstreamFailed(channel, e);
    }
}
 
Example 12
Source File: ProducerClient.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublish() throws InterruptedException{
	
	final ExecutorService pool = Executors.newFixedThreadPool(3);
	final Timer timer = new Timer(true);
	
	final AtomicInteger count = new AtomicInteger(0);
	
	final int nums = 1000;
	timer.schedule(new TimerTask() {
		
		@Override
		public void run() {
			if(count.get() == nums){
				timer.cancel();
				return;
			}
			for (int i = 0; i < 2; i++) {
				
				pool.submit(new Runnable() {			
					@Override
					public void run() {
						String topic = new Random().nextBoolean() ? "demo-topic1" : "demo-topic2";
                           topicProducer.publish(topic, new DefaultMessage(RandomStringUtils.random(5, true, true)).consumerAckRequired(new Random().nextBoolean()));
						count.incrementAndGet();
					}
				});
			}
		}
	}, 1000, 100);
	
	while(true){
		if(count.get() >= nums){
			System.out.println(">>>>>>send count:"+count.get());
			break;
		}
	}

	pool.shutdown();
}
 
Example 13
Source File: LCNRedisConnection.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Override
public void transaction() throws Exception {
    if (waitTask == null) {
        redisConnection.close();
        dataSourceService.deleteCompensates(getCompensateList());
        System.out.println("waitTask is null");
        return;
    }


    //start 结束就是全部事务的结束表示,考虑start挂掉的情况
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("自动回滚->" + getGroupId());
            dataSourceService.schedule(getGroupId(), getCompensateList(), waitTask);
        }
    }, getMaxOutTime());

    System.out.println("transaction-awaitTask->" + getGroupId());
    waitTask.awaitTask();

    timer.cancel();

    int rs = waitTask.getState();

    System.out.println("(" + getGroupId() + ")->单元事务(1:提交 0:回滚 -1:事务模块网络异常回滚 -2:事务模块超时异常回滚):" + rs);

    if (rs == 1) {
        redisConnection.exec();
    }
    if (rs != -100) {
        dataSourceService.deleteCompensates(getCompensateList());
    }
    waitTask.remove();

}
 
Example 14
Source File: FileScanner.java    From jboot with Apache License 2.0 5 votes vote down vote up
public void start() {
    if (!running) {
        timer = new Timer("Jboot-File-Scanner", true);
        task = new TimerTask() {
            public void run() {
                working();
            }
        };
        timer.schedule(task, 0, 1000L * interval);
        running = true;
    }
}
 
Example 15
Source File: Responder.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void start(Timer timer) {
    // According to draft-cheshire-dnsext-multicastdns.txt chapter "7 Responding":
    // We respond immediately if we know for sure, that we are the only one who can respond to the query.
    // In all other cases, we respond within 20-120 ms.
    //
    // According to draft-cheshire-dnsext-multicastdns.txt chapter "6.2 Multi-Packet Known Answer Suppression":
    // We respond after 20-120 ms if the query is truncated.

    boolean iAmTheOnlyOne = true;
    for (DNSQuestion question : _in.getQuestions()) {
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest(this.getName() + "start() question=" + question);
        }
        iAmTheOnlyOne = question.iAmTheOnlyOne(this.getDns());
        if (!iAmTheOnlyOne) {
            break;
        }
    }
    int delay = (iAmTheOnlyOne && !_in.isTruncated()) ? 0 : DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + JmDNSImpl.getRandom().nextInt(DNSConstants.RESPONSE_MAX_WAIT_INTERVAL - DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + 1) - _in.elapseSinceArrival();
    if (delay < 0) {
        delay = 0;
    }
    if (logger.isLoggable(Level.FINEST)) {
        logger.finest(this.getName() + "start() Responder chosen delay=" + delay);
    }
    if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
        timer.schedule(this, delay);
    }
}
 
Example 16
Source File: JCVideoPlayerStandard.java    From SprintNBA with Apache License 2.0 4 votes vote down vote up
private void startDismissControlViewTimer() {
    cancelDismissControlViewTimer();
    DISSMISS_CONTROL_VIEW_TIMER = new Timer();
    mDismissControlViewTimerTask = new DismissControlViewTimerTask();
    DISSMISS_CONTROL_VIEW_TIMER.schedule(mDismissControlViewTimerTask, 2500);
}
 
Example 17
Source File: JCVideoPlayer.java    From JCVideoPlayer with MIT License 4 votes vote down vote up
public void startProgressTimer() {
    cancelProgressTimer();
    UPDATE_PROGRESS_TIMER = new Timer();
    mProgressTimerTask = new ProgressTimerTask();
    UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
}
 
Example 18
Source File: CacheManager.java    From aliyun-log-android-sdk with MIT License 4 votes vote down vote up
public void setupTimer() {
    // 初始化定时器
    mTimer = new Timer();
    TimerTask timerTask = new CacheTimerTask(this);
    mTimer.schedule(timerTask, 30000, 30000);
}
 
Example 19
Source File: SleepyCat.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static boolean hang2() throws Exception {
    // Inspired by the imaginative test case for
    // 4850368 (process) getInputStream() attaches to forked background processes (Linux)

    // Time out was reproducible on Linux 80% of the time;
    // never on Solaris because of explicit close in Solaris-specific code.

    // Scenario: After fork(), the parent naturally closes the
    // child's stdout write end.  The child dup2's the write end
    // of its stdout onto fd 1.  On Linux, it fails to explicitly
    // close the original fd, and because of the parent's close()
    // of the fd, the child retains it.  The child thus ends up
    // with two copies of its stdout.  Thus closing one of those
    // write fds does not have the desired effect of causing an
    // EOF on the parent's read end of that pipe.
    Runtime rt = Runtime.getRuntime();
    int iterations = 10;
    Timer timer = new Timer(true);
    int timeout = 30;
    Process[] backgroundSleepers = new Process[iterations];
    TimeoutTask sleeperExecutioner = new TimeoutTask(backgroundSleepers);
    timer.schedule(sleeperExecutioner, timeout * 1000);
    byte[] buffer = new byte[10];
    String[] args =
        new String[] {UnixCommands.sh(), "-c",
                      "exec " + UnixCommands.sleep() + " "
                              + (timeout+1) + " >/dev/null"};

    for (int i = 0;
         i < backgroundSleepers.length && !sleeperExecutioner.timedOut();
         ++i) {
        backgroundSleepers[i] = rt.exec(args); // race condition here
        try {
            // should get immediate EOF, but might hang
            if (backgroundSleepers[i].getInputStream().read() != -1)
                throw new Exception("Expected EOF, got a byte");
        } catch (IOException e) {
            // Stream closed by sleeperExecutioner
            break;
        }
    }

    timer.cancel();

    destroy(backgroundSleepers);

    if (sleeperExecutioner.timedOut())
        System.out.println("Child process has two (should be one) writable pipe fds for its stdout.");
    return sleeperExecutioner.timedOut();
}
 
Example 20
Source File: Canceler.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
@Override
public void start(Timer timer) {
    timer.schedule(this, 0, DNSConstants.ANNOUNCE_WAIT_INTERVAL);
}