下面列出了怎么用java.util.TimerTask的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
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);
}
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);
}
}
@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();
}
}
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!
}
@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()));
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
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();
}
}
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);
}
}
@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);
}
@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);
}
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();
}
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);
}
}
@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);
}
/**
* 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!
}
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);
}
/**
* 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!
}
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);
}
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());
}
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);
}
}
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);
}
}
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);
}
}
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);
}
/**
* 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 );
}
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);
}
}
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);
}
}