类java.util.TimerTask源码实例Demo

下面列出了怎么用java.util.TimerTask的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: openjdk-jdk8u   文件: DelayOverflow.java
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
源代码2 项目: voip_android   文件: PeerConnectionClient.java
public void enableStatsEvents(boolean enable, int periodMs) {
    if (enable) {
        try {
            statsTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            getStats();
                        }
                    });
                }
            }, 0, periodMs);
        } catch (Exception e) {
            Log.e(TAG, "Can not schedule statistics timer", e);
        }
    } else {
        statsTimer.cancel();
    }
}
 
private void streaming() {
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            StringBuffer sb = getBuffer();
            synchronized (sb) {
                if (sb.length() > 0) {
                    String S = sb.toString();
                    flush();
                    sb.delete(0, sb.length());
                    ((T_stream) message.msg.content).text = S;
                    message.send();
                }
            }
        }
    }, 250, 250);
}
 
源代码4 项目: TencentKona-8   文件: DelayOverflow.java
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
源代码5 项目: werewolf_server   文件: TimerTest.java
@Test
    public  void timeTest(){
        Timer timer = new Timer();
        CountDownLatch countDownLatch = new CountDownLatch(1);
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                System.out.println("hahh");
                countDownLatch.countDown();
            }
        },  10000);
        try {
//            timer.cancel();  //取消定时器
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
源代码6 项目: SubServers-2   文件: 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
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.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!
}
 
源代码7 项目: SMP   文件: MusicService.java
@Override
public void onSeekComplete(MediaPlayer mp) {
    // on a 4.1 phone no bug : calling getCurrentPosition now gives the new seeked position
    // on My 2.3.6 phone, the phone seems bugged : calling now getCurrentPosition gives
    // last position. So wait the seekpos goes after the asked seekpos.
    if(seekPosBug != -1) {
        // todo: make it thread safe?
        seekPosNbLoop = seekPosMaxLoop;

        final Timer seekPosTimer = new Timer();
        seekPosTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (seekPosNbLoop-- > 0 || getCurrentPosition() >= seekPosBug) {
                    seekFinished = true;
                    seekPosBug = -1;
                    seekPosTimer.cancel();
                }
            }
        }, 300);
    }
    else {
        seekFinished = true;
    }
    Log.d("MusicService", "onSeekComplete setProgress" + RowSong.secondsToMinutes(getCurrentPosition()));
}
 
源代码8 项目: CostFed   文件: FedSumUpdate.java
/**
 * Update Index after a fixed interval
 * @param lstEndPoints List of SPARQL endpoints
 * @param interval Interval in milliseconds
 * @param outputFile Output location of index
 */
public static void updateIndexAtFixedRate(final List<String> lstEndPoints, long interval, final String outputFile) {
	Timer timer = new Timer();
	timer.scheduleAtFixedRate(new TimerTask() {public void run() { 	 try {
		FedSumGenerator generator = new FedSumGenerator(outputFile);
		long startTime = System.currentTimeMillis();
		generator.generateSummaries(lstEndPoints);
		System.out.println("Index is secessfully updated to "+ outputFile);
		System.out.println("Data Summaries Generation Time (sec): "+ (System.currentTimeMillis()-startTime)/1000);

	} catch (IOException | RepositoryException | MalformedQueryException | QueryEvaluationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	}  }, 0, interval);

	}
 
源代码9 项目: gate-core   文件: ThreadWarningSystem.java
/**
 * Monitor only deadlocks.
 */
public ThreadWarningSystem() {
  threadCheck.schedule(new TimerTask() {
    @Override
    public void run() {
      long[] ids = mbean.findMonitorDeadlockedThreads();
      if (ids != null && ids.length > 0) {
        for (Long l : ids) {
          if (!deadlockedThreads.contains(l)) {
            deadlockedThreads.add(l);
            ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH);
            fireDeadlockDetected(ti);
          }
        }
      }
    }
  }, 10, DEADLOCK_CHECK_PERIOD);
}
 
源代码10 项目: TrendrrNSQClient   文件: AbstractNSQClient.java
/**
 * connects, ready to produce.
 */
public synchronized void start() {
    this.connect();

    if (timer != null) {
        timer.cancel();
    }
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                connect();
            } catch (Throwable t) {
                log.error("Error in periodic `connect` call", t);
            }
        }
    }, lookupPeriod, lookupPeriod);
}
 
源代码11 项目: sample-videoRTC   文件: PeerConnectionClient.java
public void enableStatsEvents(boolean enable, int periodMs) {
  if (enable) {
    try {
      statsTimer.schedule(new TimerTask() {
        @Override
        public void run() {
          executor.execute(new Runnable() {
            @Override
            public void run() {
              getStats();
            }
          });
        }
      }, 0, periodMs);
    } catch (Exception e) {
      Log.e(TAG, "Can not schedule statistics timer", e);
    }
  } else {
    statsTimer.cancel();
  }
}
 
源代码12 项目: jdk8u_jdk   文件: DelayOverflow.java
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
public TimeSizeRestrictedInputStream(InputStream is,
        long timeoutMs, Action timeoutAction,
        long readLimitBytes, Action readLimitAction,
        TransformerDebug transformerDebug)
{
    this.is = useBufferedInputStream ? new BufferedInputStream(is) : is;
    this.timeoutMs = timeoutMs;
    this.timeoutAction = timeoutAction;
    this.readLimitBytes = readLimitBytes;
    this.readLimitAction = readLimitAction;
    this.transformerDebug = transformerDebug;
    
    if (timeoutMs > 0)
    {
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                timeoutFlag.set(true);
            }
        
        }, timeoutMs);
    }
}
 
源代码14 项目: helloiot   文件: ManagerTime.java
@Override
public void connect() {
    
    disconnect();
    
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private long lastepochsecond = clock.instant().getEpochSecond();
        @Override
        public void run() {
            long epochsecond = clock.instant().getEpochSecond();
            while (epochsecond - lastepochsecond > 0L) {
                lastepochsecond += 1L;
                byte[] payload = Long.toString(lastepochsecond).getBytes(StandardCharsets.UTF_8);
                consumer.accept(new EventMessage("current", payload));
            }
        }
    }, 0L, 100L);
    
}
 
源代码15 项目: SmartOrnament   文件: SplashActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // 设置全屏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash);
    //设置定时器,欢迎界面呈现2秒后跳转进入主界面
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    },2000);
}
 
源代码16 项目: openjdk-jdk8u   文件: CrashXCheckJni.java
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
源代码17 项目: WeCross   文件: Chain.java
public void start() {
    if (!running.get()) {
        running.set(true);

        blockSyncThread =
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                mainLoop();
                            }
                        });
        blockSyncThread.start();
        logger.trace("Block header sync thread started");

        mainLoopTimer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        noteMainLoop();
                    }
                },
                mainLoopInterval,
                mainLoopInterval);
    }
}
 
源代码18 项目: search-spring-boot-starter   文件: IndexAdmin.java
@PostConstruct
private void init() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            try {// 异步定时更新索引结构
                for (Map.Entry<String, IndexHelper> entry : CACHE.entrySet()) {
                    String[] keyVal = entry.getKey().split(":");
                    String index = keyVal[0];
                    String type = keyVal[1];
                    String mapping = loadIndexStruct(index, type);
                    register(index, type, mapping);
                }
            } catch (Exception e) {
                LOGGER.error("refresh.index.ERROR:" + e.getMessage());
            }
        }
    }, 10000, 5000);
}
 
源代码19 项目: NeuralNetworkAPI   文件: Metrics.java
/**
 * Starts the Scheduler which submits our data every 30 minutes.
 */
private void startSubmitting() {
    final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!plugin.isEnabled()) { // Plugin was disabled
                timer.cancel();
                return;
            }
            // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Bukkit.getScheduler().runTask(plugin, new Runnable() {
                @Override
                public void run() {
                    submitData();
                }
            });
        }
    }, 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!
}
 
源代码20 项目: JieCaoVideoPlayer-develop   文件: JCVideoPlayer.java
protected void startProgressTimer() {
    cancelProgressTimer();
    UPDATE_PROGRESS_TIMER = new Timer();
    UPDATE_PROGRESS_TIMER.schedule(new TimerTask() {
        @Override
        public void run() {
            if (getContext() != null && getContext() instanceof Activity) {
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE) {
                            setTextAndProgress(0);
                        }
                    }
                });
            }
        }
    }, 0, 300);
}
 
源代码21 项目: Skript   文件: Metrics.java
/**
  * Starts the Scheduler which submits our data every 30 minutes.
  */
 private void startSubmitting() {
     final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
     timer.scheduleAtFixedRate(new TimerTask() {
         @SuppressWarnings("synthetic-access")
@Override
         public void run() {
             if (!plugin.isEnabled()) { // Plugin was disabled
                 timer.cancel();
                 return;
             }
             // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
             // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
             Bukkit.getScheduler().runTask(plugin, new Runnable() {
                 @Override
                 public void run() {
                     submitData();
                 }
             });
         }
     }, 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!
 }
 
源代码22 项目: ganttproject   文件: FileChooserPageBase.java
private void reschedule() {
  if (myUrl == null || myUrl.getHost() == null || myUrl.getHost().length() == 0) {
    onFetchComplete(null);
    return;
  }
  myFetchedFile = null;
  onFetchComplete(null);
  isFetching = true;
  myTimer.schedule(new TimerTask() {
    final URL myUrlAtStart = myUrl;

    @Override
    public void run() {
      synchronized (myTimer) {
        if (!myUrlAtStart.equals(myUrl)) {
          reschedule();
        } else {
          fetch();
        }
      }
    }
  }, 3000);
}
 
源代码23 项目: j2objc   文件: TimerTest.java
public void testTaskNotCancelledWhenTimerCancelled() throws Exception {
    final int timeSleeping = 200;
    Timer t = new Timer();
    final AtomicLong counter = new AtomicLong();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                counter.incrementAndGet();
                Thread.sleep(timeSleeping);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    t.scheduleAtFixedRate(task, 1 /* delay */, 100 /* rate */);
    Thread.sleep(1000);
    t.cancel();
    // Returns true as the task wasn't cancelled before.
    assertTrue(task.cancel());
}
 
源代码24 项目: cxf   文件: RedeliveryQueueImpl.java
protected final synchronized void schedule() {
    if (null == manager.getTimer()) {
        return;
    }
    class RedeliverTask extends TimerTask {
        RedeliverCandidate candidate;

        RedeliverTask(RedeliverCandidate c) {
            candidate = c;
        }

        @Override
        public void run() {
            if (!candidate.isPending()) {
                candidate.initiate();
            }
        }
    }
    nextTask = new RedeliverTask(this);
    try {
        manager.getTimer().schedule(nextTask, next);
    } catch (IllegalStateException ex) {
        LOG.log(Level.WARNING, "SCHEDULE_RESEND_FAILED_MSG", ex);
    }
}
 
源代码25 项目: metron   文件: SourceHandler.java
private void initialize() throws IOException {
  LOG.debug("Initializing Source Handler");
  this.fs = FileSystem.get(new Configuration());
  this.currentFile = createOutputFile();
  LOG.debug("Source Handler initialized with starting file: {}", currentFile);
  if(this.rotationPolicy instanceof TimedRotationPolicy){
    long interval = ((TimedRotationPolicy)this.rotationPolicy).getInterval();
    this.rotationTimer = new Timer(true);
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        try {
          LOG.debug("Rotating output file from TimerTask");
          rotateOutputFile();
        } catch(IOException e){
          LOG.warn("IOException during scheduled file rotation.", e);
        }
      }
    };
    this.rotationTimer.scheduleAtFixedRate(task, interval, interval);
  }
}
 
源代码26 项目: big-c   文件: ContainerMetrics.java
private synchronized void scheduleTimerTaskIfRequired() {
  if (flushPeriodMs > 0) {
    // Lazily initialize timer
    if (timer == null) {
      this.timer = new Timer("Metrics flush checker", true);
    }
    TimerTask timerTask = new TimerTask() {
      @Override
      public void run() {
        synchronized (ContainerMetrics.this) {
          if (!finished) {
            flushOnPeriod = true;
          }
        }
      }
    };
    timer.schedule(timerTask, flushPeriodMs);
  }
}
 
源代码27 项目: bitseal   文件: ViewErrorsActivity.java
protected void onResume() 
{
	super.onResume();
	
	// Check for new log lines regularly and update the ListView if any are found
       refreshListTask = new TimerTask()
    {
        @Override
        public void run() 
        {
            runOnUiThread(new Runnable()
            {
                public void run() 
                {
                	if (checkForNewLines())
                	{
                		updateListView();
                	}
                }
            });
        }
    };
    new Timer().schedule(refreshListTask, 0, UPDATE_FREQUENCY_MILLISECONDS);
}
 
源代码28 项目: RipplePower   文件: AbstractWebSocket.java
/**
 * Start the connection lost timer
 */
protected void startConnectionLostTimer() {
    if (this.connectionLostTimeout <= 0) {
        if (WebSocketImpl.DEBUG)
            System.out.println("Connection lost timer deactivated");
        return;
    }
    if (WebSocketImpl.DEBUG)
        System.out.println("Connection lost timer started");
    cancelConnectionLostTimer();
    connectionLostTimer = new Timer();
    connectionLostTimerTask = new TimerTask() {
        @Override
        public void run() {
            Collection<WebSocket> con = connections();
            synchronized ( con ) {
                long current = (System.currentTimeMillis()-(connectionLostTimeout * 1500));
                for( WebSocket conn : con ) {
                    if (conn instanceof WebSocketImpl) {
                        if( ((WebSocketImpl)conn).getLastPong() < current ) {
                            if (WebSocketImpl.DEBUG)
                                System.out.println("Closing connection due to no pong received: " + conn.toString());
                            conn.close( CloseFrame.ABNORMAL_CLOSE );
                        } else {
                            conn.sendPing();
                        }
                    }
                }
            }
        }
    };
    connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,connectionLostTimeout * 1000, connectionLostTimeout * 1000 );
}
 
源代码29 项目: DevToolBox   文件: Loading.java
public void startMainApp(Stage ms) {
    try {
        long time = System.currentTimeMillis();
        Stage stage = new Stage();
        stage.setTitle(Undecorator.LOC.getString("AppName") + " " + Undecorator.LOC.getString("Version") + " 版本号:" + Undecorator.LOC.getString("VersionCode"));
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
        Region root = (Region) fxmlLoader.load();
        final UndecoratorScene undecoratorScene = new UndecoratorScene(stage, root);
        stage.setOnCloseRequest((WindowEvent we) -> {
            we.consume();
            undecoratorScene.setFadeOutTransition();
        });
        undecoratorScene.getStylesheets().add("/styles/main.css");
        stage.setScene(undecoratorScene);
        stage.toFront();
        stage.getIcons().add(new Image(getClass().getResourceAsStream("/skin/icon.png")));
        stage.setOnShown((event) -> {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    Platform.runLater(() -> {
                        ms.close();
                    });
                }
            }, 1000);
        });
        stage.show();
        ApplicationStageManager.putStageAndController(ApplicationStageManager.StateAndController.MAIN, stage, fxmlLoader.getController());
        LOGGER.info("主页面加载耗时:" + (System.currentTimeMillis() - time) + "毫秒");
    } catch (IOException ex) {
        LOGGER.error("启动主程序异常", ex);
    }
}
 
源代码30 项目: xDrip   文件: G5CollectionService.java
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
 类所在包
 同包方法