下面列出了怎么用java.util.Timer的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void start() {
int bucketSize = checkBucketNum(properties.getBucketSize());
if (isRuning.compareAndSet(false, true)) {
for (int i = 1; i <= bucketSize; i++) {
String bName = NamedUtil.buildBucketName(properties.getPrefix(), properties.getName(), i);
BucketTask task = new BucketTask(bName);
task.setJobOperationService(jobOperationService);
task.setPoolName(NamedUtil.buildPoolName(properties.getPrefix(), properties.getName(), properties
.getOriginPool()));
task.setReadyName(NamedUtil.buildPoolName(properties.getPrefix(), properties.getName(), properties
.getReadyName()));
task.setProperties(properties);
task.setLock(lock);
String threadName = String.format(THREAD_NAME, i);
Timer timer = new Timer(threadName, daemon);
timer.schedule(task, 500, properties.getBuckRoundRobinTime());
HOLD_TIMES.put(threadName, timer);
LOGGER.info(String.format("Starting Bucket Thead %s ....", threadName));
}
}
}
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);
}
}
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 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 static void executeJobExecutorForTime(ProcessEngineConfiguration processEngineConfiguration, long maxMillisToWait, long intervalMillis) {
AsyncExecutor asyncExecutor = processEngineConfiguration.getAsyncExecutor();
asyncExecutor.start();
try {
Timer timer = new Timer();
InteruptTask task = new InteruptTask(Thread.currentThread());
timer.schedule(task, maxMillisToWait);
try {
while (!task.isTimeLimitExceeded()) {
Thread.sleep(intervalMillis);
}
} catch (InterruptedException e) {
// ignore
} finally {
timer.cancel();
}
} finally {
asyncExecutor.shutdown();
}
}
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));
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
storageTimer = new Timer();
secondatyStorageTimer = new Timer();
usbStorageTimer = new Timer();
processTimer = new Timer();
storageStats = (HomeItem) view.findViewById(R.id.storage_stats);
secondayStorageStats = (HomeItem) view.findViewById(R.id.seconday_storage_stats);
usbStorageStats = (HomeItem) view.findViewById(R.id.usb_storage_stats);
memoryStats = (HomeItem) view.findViewById(R.id.memory_stats);
recents = (TextView)view.findViewById(R.id.recents);
recents_container = view.findViewById(R.id.recents_container);
mShortcutsRecycler = (RecyclerView) view.findViewById(R.id.shortcuts_recycler);
mRecentsRecycler = (RecyclerView) view.findViewById(R.id.recents_recycler);
roots = DocumentsApplication.getRootsCache(getActivity());
mHomeRoot = roots.getHomeRoot();
showRecents();
showData();
}
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();
}
@Test
public void testMem() throws InterruptedException
{
Timer timer = new Timer();
MEMTimerTask task = new MEMTimerTask(
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]+ "/" + data[3]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
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 toFront() {
try {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
getMyStage().toFront();
if (topCheck != null) {
topCheck.setSelected(AppVariables.getUserConfigBoolean(baseName + "Top", true));
if (topCheck.isVisible()) {
getMyStage().setAlwaysOnTop(topCheck.isSelected());
}
}
timer = null;
});
}
}, 1000);
} catch (Exception e) {
logger.error(e.toString());
}
}
@Override
public void startCountDown() {
countDownTimer = new Timer();
countDownTimer.schedule(new TimerTask() {
private int i = 0;
@Override
public void run() {
if (++i > 10) {
stopCountDown();
mHandler.sendEmptyMessage(NaviSetLineActivity.MSG_START_NAV);
} else {
Message msg = new Message();
msg.what = NaviSetLineActivity.MSG_UPDATE_COUNTDOWN;
msg.arg1 = 10 - i;
mHandler.sendMessage(msg);
}
}
}, 1000, 1000);
}
public void doInit() throws ServletException {
synchronized(s_initialized) {
if ( !s_initialized ) {
super.doInit();
// Initialize the core service
initCoreService();
// Initialize the data service
initDataService();
// Initialize resources from other plugins
initDynamicResources();
// Schedule the timer task to run every 30 seconds
IStatisticsProvider provider = ProviderFactory.getStatisticsProvider();
if ( provider != null ) {
s_statsTimer = new Timer(true);
s_statsTimer.schedule(s_statsTimerTask, STATS_TIMER_INTERVAL, STATS_TIMER_INTERVAL);
}
s_initialized = true;
DAS_LOGGER.getLogger().fine("DasServlet initialized."); // $NON-NLS-1$
}
}
}
CaptureReadHandler(String identifier, CaptureReadCompletionHandler result, int timeout, @Nullable CaptureReadCompletionHandler.TimeoutAction timeoutAction, boolean isNotifyOmitted) {
mIdentifier = identifier;
mResult = result;
mIsNotifyOmitted = isNotifyOmitted;
// Setup timeout if not zero
if (timeout > 0 && timeoutAction != null) {
mTimeoutAction = timeoutAction;
mTimeoutTimer = new Timer();
if (kProfileTimeouts) {
mTimeoutStartingMillis = System.currentTimeMillis();
Log.d(TAG, "Start timeout: " + identifier + ". millis:" + mTimeoutStartingMillis);
}
mTimeoutTimer.schedule(new TimerTask() {
@Override
public void run() {
if (kProfileTimeouts) {
Log.d(TAG, "Fire timeout: " + identifier + ". elapsed millis:" + (System.currentTimeMillis() - mTimeoutStartingMillis));
}
mResult.read(kPeripheralReadTimeoutError, null);
mTimeoutAction.execute(identifier);
}
}, timeout);
}
}
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();
}
private void sendContinuous(final String deviceId, final String datastream, final float minValue, final float maxValue, int period) {
TimerTask task = new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
sendOnce(deviceId, datastream, minValue, maxValue);
}
});
}
};
mSendDataTimer = new Timer(true);
mSendDataTimer.schedule(task, 0, period * 1000);
mSendContinuousButton.setText(R.string.stop_sending);
mDeviceIdLayout.setEnabled(false);
mDataStreamLayout.setEnabled(false);
mMinValueLayout.setEnabled(false);
mMaxValueLayout.setEnabled(false);
mPeriodLayout.setEnabled(false);
mSendOneceButton.setEnabled(false);
mSending = true;
}
/**
* 发送验证码
*
* @param phone
* the phone
*/
private void sendVerifyCode(final String phone) {
String CaptchaCode = etInputCaptchaCode_farget.getText().toString();
dialog.show();
btnReGetCode.setEnabled(false);
btnReGetCode.setBackgroundResource(R.drawable.button_gray_short);
secondleft = 60;
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 倒计时通知
handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal());
}
}, 1000, 1000);
// 发送请求验证码指令
// mCenter.cRequestSendVerifyCode(phone);
// 发送请求验证码指令
Log.i("AppTest", tokenString + ", " + captchaidString + ", " + CaptchaCode + ", " + phone);
mCenter.cRequestSendVerifyCode(tokenString, captchaidString, CaptchaCode, phone);
}
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 createPeerConnectionFactory(final Context context,
final PeerConnectionParameters peerConnectionParameters, final PeerConnectionEvents events) {
this.peerConnectionParameters = peerConnectionParameters;
this.events = events;
// Reset variables to initial states.
this.context = null;
factory = null;
videoCapturerStopped = false;
isError = false;
mediaStream = null;
videoCapturer = null;
renderVideo = true;
localVideoTrack = null;
remoteVideoTrack = null;
localVideoSender = null;
enableAudio = true;
localAudioTrack = null;
statsTimer = new Timer();
executor.execute(new Runnable() {
@Override
public void run() {
createPeerConnectionFactoryInternal(context);
}
});
}
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
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final AsyncContext asyncContext = req.startAsync();
// DON'T TRY THIS AT HOME: Working with threads in a Container !!
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
asyncContext.getResponse().getWriter().println(new Date() + ": Asynchronous Response");
System.out.println("Release pending HTTP connection");
asyncContext.complete();
} catch (IOException e) {
e.printStackTrace();
}
}
}, 10 * 1000);
resp.getWriter().println(new Date() + ": Async Servlet returns leaving the connection open");
}
@Override
public void onCreate() {
super.onCreate();
LogUtil.i(TAG, "chatMainService onCreate");
context = TokApplication.getInstance();
keepRunning = true;
Runnable start = new Runnable() {
@Override
public void run() {
ToxManager.getManager().initTox(TokApplication.getInstance());
final ToxCallbackListener toxCallbackListener = new ToxCallbackListener(context);
timer = new Timer(true);
isRunning = true;
try {
task = new TimerTask() {
public void run() {
if (keepRunning) {
if (NetUtils.isNetworkAvailable()) {
if (keepRunning) {
LogUtil.i(TAG,
"coreManager:" + ToxManager.getManager().hashCode());
ToxManager.getManager().iterate(toxCallbackListener);
}
}
} else {
stopTimer();
}
}
};
} catch (Exception e) {
e.printStackTrace();
}
timer.scheduleAtFixedRate(task, 200, 200);
}
};
serviceThread = new Thread(start);
serviceThread.start();
}
/**
* @throws Exception If failed.
*/
@Test
public void testSemaphoreNonFailoverSafe() throws Exception {
try (IgniteSemaphore sem = grid(0).semaphore(STRUCTURE_NAME, 20, false, true)) {
Ignite g = startGrid(NEW_IGNITE_INSTANCE_NAME);
IgniteSemaphore sem2 = g.semaphore(STRUCTURE_NAME, 20, false, false);
sem2.acquire(20);
assertEquals(0, sem.availablePermits());
new Timer().schedule(new TimerTask() {
@Override public void run() {
stopGrid(NEW_IGNITE_INSTANCE_NAME);
}
}, 2000);
try {
sem.acquire(1);
}
catch (IgniteInterruptedException ignored) {
// Expected exception.
return;
}
}
fail("Thread hasn't been interrupted");
}
synchronized void start() {
if (started) {
return;
}
Timer timer = new Timer("Timer thread for monitoring ", true);
TimerTask task = new TimerTask() {
public void run() {
update();
}
};
long millis = period * 1000;
timer.scheduleAtFixedRate(task, millis, millis);
started = true;
}
/**
* Stops all delayed events.
*/
public void stop() {
for (Timer timer : delayedEvents.values()) {
timer.cancel();
}
delayedEvents.clear();
}
@Override
public void init( ServletConfig config ) throws ServletException
{
super.init( config );
statistics = new Statistics();
matchSchemeOnRedirect = Boolean.valueOf( System
.getProperty( Constants.PROPERTY_PREFIX + MATCH_SCHEME_ON_REDIRECT,
matchSchemeOnRedirect.toString() ) );
try
{
LoadConfigTask loadConfigTask = new LoadConfigTask();
loadConfigTask.loadData();
if ( config != null )
{
timer = new Timer();
timer.schedule( loadConfigTask, CHECK_CONFIG_FILES, CHECK_CONFIG_FILES );
}
}
catch ( Exception e )
{
throw new ServletException( e );
}
}
/**
* Constructs this object.
*
* @param config the {@code Config} instance
* @param inst the {@code Instrumentation} instance.
* @param activity the start {@code Activity}
* @param sleeper the {@code Sleeper} instance
*/
public ActivityUtils(Config config, Instrumentation inst, Activity activity, Sleeper sleeper) {
this.config = config;
this.inst = inst;
this.activity = activity;
this.sleeper = sleeper;
createStackAndPushStartActivity();
activitySyncTimer = new Timer();
activitiesStoredInActivityStack = new Stack<String>();
setupActivityMonitor();
setupActivityStackListener();
}
/**
* Tests that {@link LocalInputChannel#retriggerSubpartitionRequest(Timer, int)} would throw
* {@link PartitionNotFoundException} which is set onto the input channel then.
*/
@Test
public void testChannelErrorWhileRetriggeringRequest() {
final SingleInputGate inputGate = createSingleInputGate(1);
final LocalInputChannel localChannel = createLocalInputChannel(inputGate, new ResultPartitionManager());
final Timer timer = new Timer(true) {
@Override
public void schedule(TimerTask task, long delay) {
task.run();
try {
localChannel.checkError();
fail("Should throw a PartitionNotFoundException.");
} catch (PartitionNotFoundException notFound) {
assertThat(localChannel.partitionId, Matchers.is(notFound.getPartitionId()));
} catch (IOException ex) {
fail("Should throw a PartitionNotFoundException.");
}
}
};
try {
localChannel.retriggerSubpartitionRequest(timer, 0);
} finally {
timer.cancel();
}
}
private void mountMain() {
if (mainFile.exists()) {
AliteLog.d(TAG, "Mounting main file...");
AliteLog.d(TAG, "Scheduling mount checker...");
// I have left the mount checker in place but extended it's initial activation to
// 8 seconds. If it is clear that this modification is working the mountchecker
// can be removed altogether
(new Timer()).schedule(mainChecker, 8000);
sm.mountObb(mainFile.getAbsolutePath(), null, mainObbStateChangeListener );
} else {
AliteLog.d(TAG, "Patch file not found");
}
}
private void close() {
TimerTask shutdownTask = new TimerTask() {
@Override
public void run() {
((AbstractApplicationContext) applicationContext).close();
}
};
Timer shutdownTimer = new Timer();
shutdownTimer.schedule(shutdownTask, TimeUnit.SECONDS.toMillis(20));
}