当前位置: 首页>>代码示例>>Java>>正文


Java ScheduledExecutorService类代码示例

本文整理汇总了Java中java.util.concurrent.ScheduledExecutorService的典型用法代码示例。如果您正苦于以下问题:Java ScheduledExecutorService类的具体用法?Java ScheduledExecutorService怎么用?Java ScheduledExecutorService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ScheduledExecutorService类属于java.util.concurrent包,在下文中一共展示了ScheduledExecutorService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: HTTPconThread

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
public HTTPconThread(int id,URLdetails obj,int time){
	this.obj=obj;
	this.id = id;
	this.time=time;
	this.index = Controller.getList().indexOf(obj);
	final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new Runnable() {
		@Override
		public void run() {
			if(Controller.getList().indexOf(obj)==-1){
				executorService.shutdown();
			}
			testIt(obj.getUrl());
		}
	}, 0, time, TimeUnit.SECONDS);
}
 
开发者ID:naeemkhan12,项目名称:websiteMonitor,代码行数:17,代码来源:HTTPconThread.java

示例2: getUploadSucceededListener

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
@SuppressWarnings("serial")
private SucceededListener getUploadSucceededListener() {
    return new SucceededListener() {

        @Override
        public void uploadSucceeded(SucceededEvent event) {
            log.info("Upload Successful! Analyzing Uploaded Image.....");
            final ProgressIndicatorWindow progressIndicatorWindow = new ProgressIndicatorWindow();

            progressIndicatorWindow.setWidth("200px");
            progressIndicatorWindow.setHeight("100px");
            progressIndicatorWindow.setCaption("Processing image ...");

            UI.getCurrent().addWindow(progressIndicatorWindow);
            progressIndicatorWindow.bringToFront();

            Runnable serviceCall = uploadValidationService(progressIndicatorWindow, event);

            ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
            exec.schedule(serviceCall, 1, TimeUnit.MILLISECONDS);
        }
    };
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:24,代码来源:ImportApplianceSoftwareVersionWindow.java

示例3: init

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
public void init(){
	String cleanTime = logCleanTime;
	Date nextExeucteTime = calcNextExecuteTime(cleanTime);
	long initialDelay = nextExeucteTime.getTime() - System.currentTimeMillis();
	
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("CleanLogJob",true));
	executor.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			try{
				if(master.hasLeaderShip()){
					Calendar instance = Calendar.getInstance();
					instance.add(Calendar.DATE, -logReservedDays);
					LOG.info("START CLEAN EXPIRED TRANSACTION LOGS.DAYS:" + logReservedDays);
					logWritter.cleanFinishedLogs(applicationName, instance.getTime());
					LOG.info("END CLEAN EXPIRED TRANSACTION LOGS.DAYS");
				}else{
					LOG.info("NOT MASTER,do not execute transaction log clean job");
				}
			}catch(Exception e){
				LOG.error("execute clean job error!",e);
			}
		}
	}, initialDelay, 24l*60*60*1000 , TimeUnit.MILLISECONDS);
}
 
开发者ID:QNJR-GROUP,项目名称:EasyTransaction,代码行数:26,代码来源:DataBaseTransactionLogCleanJob.java

示例4: testDelay

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
@Test
public void testDelay() throws InterruptedException {
    ScheduledExecutorService ses =
        Executors.newSingleThreadScheduledExecutor();

    SingletonTask st1 = new SingletonTask(ses, new Runnable() {
        @Override
        public void run() {
            ran += 1;
            time = System.nanoTime();
        }
    });
    st1.reschedule(10, TimeUnit.MILLISECONDS);
    assertFalse("Check that task hasn't run yet", ran > 0);

    ses.shutdown();
    ses.awaitTermination(5, TimeUnit.SECONDS);

    assertEquals("Check that task ran", 1, ran);
}
 
开发者ID:nsg-ethz,项目名称:iTAP-controller,代码行数:21,代码来源:SingletonTaskTest.java

示例5: ExperimentalBitmapAnimationDrawableFactory

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
public ExperimentalBitmapAnimationDrawableFactory(
    AnimatedDrawableBackendProvider animatedDrawableBackendProvider,
    ScheduledExecutorService scheduledExecutorServiceForUiThread,
    ExecutorService executorServiceForFramePreparing,
    MonotonicClock monotonicClock,
    PlatformBitmapFactory platformBitmapFactory,
    CountingMemoryCache<CacheKey, CloseableImage> backingCache,
    Supplier<Integer> cachingStrategySupplier,
    Supplier<Integer> numberOfFramesToPrepareSupplier) {
  mAnimatedDrawableBackendProvider = animatedDrawableBackendProvider;
  mScheduledExecutorServiceForUiThread = scheduledExecutorServiceForUiThread;
  mExecutorServiceForFramePreparing = executorServiceForFramePreparing;
  mMonotonicClock = monotonicClock;
  mPlatformBitmapFactory = platformBitmapFactory;
  mBackingCache = backingCache;
  mCachingStrategySupplier = cachingStrategySupplier;
  mNumberOfFramesToPrepareSupplier = numberOfFramesToPrepareSupplier;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:19,代码来源:ExperimentalBitmapAnimationDrawableFactory.java

示例6: AnomalyDetector

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
/**
 * Package private constructor for unit test.
 */
AnomalyDetector(LinkedBlockingDeque<Anomaly> anomalies,
                long anomalyDetectionIntervalMs,
                KafkaCruiseControl kafkaCruiseControl,
                AnomalyNotifier anomalyNotifier,
                GoalViolationDetector goalViolationDetector,
                BrokerFailureDetector brokerFailureDetector,
                ScheduledExecutorService detectorScheduler) {
  _anomalies = anomalies;
  _anomalyDetectionIntervalMs = anomalyDetectionIntervalMs;
  _anomalyNotifier = anomalyNotifier;
  _goalViolationDetector = goalViolationDetector;
  _brokerFailureDetector = brokerFailureDetector;
  _kafkaCruiseControl = kafkaCruiseControl;
  _detectorScheduler = detectorScheduler;
  _shutdown = false;
  _brokerFailureRate = new Meter();
  _goalViolationRate = new Meter();
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:22,代码来源:AnomalyDetector.java

示例7: startNotificationPull

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
/**
 * Starts notification pull.
 */
public void startNotificationPull() {
    if (isPullingActive()) {
        api.getLogger().logInfo("Notification pull is already working.");
        return;
    }
    final Runnable cachingSingleAction = createCachingSingleAction();
    pullHandle = null;
    if (pullThreads instanceof ScheduledExecutorService) {
        pullHandle = ((ScheduledExecutorService) pullThreads).scheduleWithFixedDelay(cachingSingleAction, 0, 50,
                TimeUnit.MILLISECONDS);
    } else {
        pullHandle = pullThreads.submit(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    cachingSingleAction.run();
                }

            }
        });
    }

}
 
开发者ID:ARMmbed,项目名称:mbed-cloud-sdk-java,代码行数:28,代码来源:NotificationCache.java

示例8: renamingDecorator

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
/**
 * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its
 * tasks run in.
 *
 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed
 * right before each task is run. The renaming is best effort, if a {@link SecurityManager}
 * prevents the renaming then it will be skipped but the tasks will still execute.
 *
 *
 * @param service The executor to decorate
 * @param nameSupplier The source of names for each task
 */
@GwtIncompatible // concurrency
static ScheduledExecutorService renamingDecorator(
    final ScheduledExecutorService service, final Supplier<String> nameSupplier) {
  checkNotNull(service);
  checkNotNull(nameSupplier);
  if (isAppEngine()) {
    // AppEngine doesn't support thread renaming, so don't even try.
    return service;
  }
  return new WrappingScheduledExecutorService(service) {
    @Override
    protected <T> Callable<T> wrapTask(Callable<T> callable) {
      return Callables.threadRenaming(callable, nameSupplier);
    }

    @Override
    protected Runnable wrapTask(Runnable command) {
      return Callables.threadRenaming(command, nameSupplier);
    }
  };
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:34,代码来源:MoreExecutors.java

示例9: scheduleRetry

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
private <T> void scheduleRetry(
    Throwable e, ScheduledExecutorService retryExecutor,
    CheckedSupplier<? extends CompletionStage<T>, ?> supplier, CompletableFuture<T> future) {
  try {
    Maybe<ExceptionPlan.Execution<Delay<?>>, ?> maybeRetry = plan.execute(e);
    maybeRetry.ifPresent(execution -> {
      future.exceptionally(x -> {
        addSuppressedTo(x, e);
        return null;
      });
      if (future.isDone()) return;  // like, canceled immediately before scheduling.
      @SuppressWarnings("unchecked")  // delay came from upon(), which enforces <? super E>.
      Delay<Throwable> delay = (Delay<Throwable>) execution.strategy();
      Retryer nextRound = new Retryer(execution.remainingExceptionPlan());
      Failable retry = () -> nextRound.invokeWithRetry(supplier, retryExecutor, future);
      delay.asynchronously(e, retry, retryExecutor, future);
    });
    maybeRetry.catching(future::completeExceptionally);
  } catch (Throwable unexpected) {
    addSuppressedTo(unexpected, e);
    throw unexpected;
  }
}
 
开发者ID:google,项目名称:mug,代码行数:24,代码来源:Retryer.java

示例10: scheduler

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
@Override
protected ScheduledExecutorService scheduler() {
  if (this.scheduler == null) {
    synchronized (this) {
      if (this.scheduler == null) {
        ThreadFactory timerFactory = new ThreadFactoryBuilder()
            .setNameFormat("AsyncReporter-" + id + "-timer-%d")
            .setDaemon(true)
            .build();
        ScheduledThreadPoolExecutor timerPool = new ScheduledThreadPoolExecutor(timerThreads, timerFactory);
        timerPool.setRemoveOnCancelPolicy(true);
        this.scheduler = timerPool;
        return timerPool;
      }
    }
  }
  return scheduler;
}
 
开发者ID:tramchamploo,项目名称:buffer-slayer,代码行数:19,代码来源:AsyncReporter.java

示例11: create

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
public static ModbusMaster create ( final BundleContext context, final ScheduledExecutorService executor, final String id, final NioProcessor processor, final Map<String, String> parameters ) throws Exception
{
    final ModbusMaster device = new ModbusMaster ( context, id, executor, processor, "ModbusMaster", "modbus" );

    try
    {
        device.configure ( parameters );
    }
    catch ( final Exception e )
    {
        // dispose what was already created
        device.dispose ();
        throw e;
    }

    return device;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:18,代码来源:ModbusMaster.java

示例12: Poller

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
@Inject
Poller(@IoExecutor Executor ioExecutor,
		@Scheduler ScheduledExecutorService scheduler,
		ConnectionManager connectionManager,
		ConnectionRegistry connectionRegistry, PluginManager pluginManager,
		SecureRandom random, Clock clock) {
	this.ioExecutor = ioExecutor;
	this.scheduler = scheduler;
	this.connectionManager = connectionManager;
	this.connectionRegistry = connectionRegistry;
	this.pluginManager = pluginManager;
	this.random = random;
	this.clock = clock;
	lock = new ReentrantLock();
	tasks = new HashMap<TransportId, PollTask>();
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:17,代码来源:Poller.java

示例13: MackerelReporter

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
protected MackerelReporter(MetricRegistry registry,
                           MackerelSender mackerel,
                           Clock clock,
                           String prefix,
                           TimeUnit rateUnit,
                           TimeUnit durationUnit,
                           MetricFilter filter,
                           ScheduledExecutorService executor,
                           boolean shutdownExecutorOnStop,
                           Set<MetricAttribute> disabledMetricAttributes) {
    super(registry, "mackerel-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop,
            disabledMetricAttributes);
    this.mackerel = mackerel;
    this.clock = clock;
    this.prefix = prefix;
}
 
开发者ID:kawasima,项目名称:metrics-mackerel,代码行数:17,代码来源:MackerelReporter.java

示例14: testBasic

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
@Test
public void testBasic() throws InterruptedException {
    ScheduledExecutorService ses =
        Executors.newSingleThreadScheduledExecutor();

    SingletonTask st1 = new SingletonTask(ses, new Runnable() {
        @Override
        public void run() {
            ran += 1;
        }
    });
    st1.reschedule(0, null);
    ses.shutdown();
    ses.awaitTermination(5, TimeUnit.SECONDS);

    assertEquals("Check that task ran", 1, ran);
}
 
开发者ID:xuraylei,项目名称:fresco_floodlight,代码行数:18,代码来源:SingletonTaskTest.java

示例15: JdbcQuery

import java.util.concurrent.ScheduledExecutorService; //导入依赖的package包/类
public JdbcQuery ( final JdbcDao jdbcStorageDao, final Filter filter, final ScheduledExecutorService executor, final List<JdbcQuery> openQueries ) throws SQLException, NotSupportedException
{
    openQueries.add ( this );
    this.openQueries = new WeakReference<List<JdbcQuery>> ( openQueries );
    this.resultSet = jdbcStorageDao.queryEvents ( filter );
    this.statement = this.resultSet.getStatement ();
    this.hasMore = this.resultSet.next ();
    this.future = executor.schedule ( new Callable<Boolean> () {
        @Override
        public Boolean call ()
        {
            logger.warn ( "Query '{}' was open for over an hour, or service is being shut down, and will now be closed automatically" );
            dispose ();
            return true;
        }
    }, 1, TimeUnit.HOURS );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:18,代码来源:JdbcQuery.java


注:本文中的java.util.concurrent.ScheduledExecutorService类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。