java.util.Timer Java Examples

The following examples show how to use java.util.Timer. 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: BucketQueueManager.java    From sdmq with Apache License 2.0 6 votes vote down vote up
@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));
        }

    }
}
 
Example #2
Source File: DelayOverflow.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #3
Source File: DelayOverflow.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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));
    }
}
 
Example #4
Source File: CrashXCheckJni.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: JobTestHelper.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #6
Source File: DelayOverflow.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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));
    }
}
 
Example #7
Source File: HomeFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source File: CrashXCheckJni.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #9
Source File: MEMTest.java    From GTTools with MIT License 6 votes vote down vote up
@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);
}
 
Example #10
Source File: CrashXCheckJni.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #11
Source File: BaseController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #12
Source File: NaviSetLinePresenter.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: DasServlet.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
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$
        }
    }
}
 
Example #14
Source File: BlePeripheral.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #15
Source File: CrashXCheckJni.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #16
Source File: DataSimFragment.java    From AndroidSDK with MIT License 6 votes vote down vote up
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;
}
 
Example #17
Source File: ForgetPswActivity.java    From Gizwits-SmartSocket_Android with MIT License 6 votes vote down vote up
/**
 * 发送验证码
 * 
 * @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);
}
 
Example #18
Source File: CrashXCheckJni.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #19
Source File: PeerConnectionClient.java    From janus-gateway-android with MIT License 6 votes vote down vote up
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);
    }
  });
}
 
Example #20
Source File: Metrics.java    From SubServers-2 with Apache License 2.0 6 votes vote down vote up
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!
}
 
Example #21
Source File: AsyncServlet.java    From training with MIT License 6 votes vote down vote up
@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");
}
 
Example #22
Source File: ChatMainService.java    From Tok-Android with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example #23
Source File: GridCacheAbstractDataStructuresFailoverSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @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");
}
 
Example #24
Source File: StatisticsCollector.java    From RDFS with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: DelayedExecuter.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Stops all delayed events.
 */
public void stop() {
    for (Timer timer : delayedEvents.values()) {
        timer.cancel();
    }
    delayedEvents.clear();
}
 
Example #26
Source File: RedirectServlet.java    From rdap_bootstrap_server with ISC License 5 votes vote down vote up
@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 );
    }
}
 
Example #27
Source File: ActivityUtils.java    From AndroidRipper with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #28
Source File: LocalInputChannelTest.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example #29
Source File: ObbExpansionsManager.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
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");
    }
}
 
Example #30
Source File: PlainTextEmailSchedulingApplication.java    From spring-boot-email-tools with Apache License 2.0 5 votes vote down vote up
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));
}