Java Code Examples for java.util.concurrent.ScheduledExecutorService

The following are top voted examples for showing how to use java.util.concurrent.ScheduledExecutorService. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: websiteMonitor   File: HTTPconThread.java   Source Code and License 11 votes vote down vote up
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);
}
 
Example 2
Project: iTAP-controller   File: SingletonTaskTest.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 3
Project: osc-core   File: ImportApplianceSoftwareVersionWindow.java   Source Code and License 6 votes vote down vote up
@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);
        }
    };
}
 
Example 4
Project: EasyTransaction   File: DataBaseTransactionLogCleanJob.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 5
Project: cruise-control   File: AnomalyDetector.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Project: mbed-cloud-sdk-java   File: NotificationCache.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
                }

            }
        });
    }

}
 
Example 7
Project: guava-mock   File: MoreExecutors.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 8
Project: mug   File: Retryer.java   Source Code and License 6 votes vote down vote up
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;
  }
}
 
Example 9
Project: buffer-slayer   File: AsyncReporter.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 10
Project: neoscada   File: ModbusMaster.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 11
Project: Nird2   File: Poller.java   Source Code and License 6 votes vote down vote up
@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>();
}
 
Example 12
Project: metrics-mackerel   File: MackerelReporter.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 13
Project: fresco_floodlight   File: SingletonTaskTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: neoscada   File: JdbcQuery.java   Source Code and License 6 votes vote down vote up
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 );
}
 
Example 15
Project: ETUmulator   File: UARTTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test of read method, of class UART.
 *
 * @throws java.lang.InterruptedException
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 */
@Test
public void testRead() throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Semaphore semaphore = new Semaphore(0);
    mockInput = '5';
    Future<Void> future = executor.submit(() -> {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ScheduledFuture<?> releaserHandle = scheduler.schedule(() -> {
            semaphore.release();
        }, 5, TimeUnit.SECONDS);
        uart.read();
        releaserHandle.get(5, TimeUnit.SECONDS);
        return null;
    });
    semaphore.tryAcquire(15, TimeUnit.SECONDS);
    uart.feed(mockInput);
    future.get(25, TimeUnit.SECONDS);
    assertEquals("UART read result is wrong.", mockInput, registerFile.getValue("r0"));
}
 
Example 16
Project: util4j   File: TestTreeMap.java   Source Code and License 5 votes vote down vote up
public void runTest()
{
	ScheduledExecutorService s=new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("Scheduled"));
	ExecutorService es=Executors.newCachedThreadPool();
	es.execute(this::writeTest);
	es.execute(this::writeTest);
	es.execute(this::writeTest);
	es.execute(this::writeTest);
	es.execute(this::readTest);
	es.execute(this::readTest);
	es.execute(this::readTest);
	es.execute(this::readTest);
	es.execute(this::readTest);
	es.execute(this::readTest);
	s.scheduleAtFixedRate(this::printInfo,5, 5, TimeUnit.SECONDS);
}
 
Example 17
Project: ZhidaoDaily-android   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
            service.schedule(new Runnable() {
                @Override
                public void run() {
                    if (!isFinishing()) {
                        isExit = false;
                    }
                }
            }, 2000, TimeUnit.MILLISECONDS);
        } else {
            isExit = true;
            this.finish();
        }
    }
    return false;
}
 
Example 18
Project: neoscada   File: ScriptSourceFactory.java   Source Code and License 5 votes vote down vote up
public ScriptSourceFactory ( final BundleContext context, final ScheduledExecutorService executor, final EventProcessor eventProcessor ) throws InvalidSyntaxException
{
    super ( context );
    this.executor = executor;

    this.eventProcessor = eventProcessor;

    this.objectPool = new ObjectPoolImpl<DataSource> ();
    this.poolRegistration = ObjectPoolHelper.registerObjectPool ( context, this.objectPool, DataSource.class );

    this.poolTracker = new ObjectPoolTracker<DataSource> ( context, DataSource.class.getName () );
    this.poolTracker.open ();
}
 
Example 19
Project: neoscada   File: HSDBItemController.java   Source Code and License 5 votes vote down vote up
public HSDBItemController ( final String id, final ScheduledExecutorService executor, final BundleContext context, final HSDBValueSource source )
{
    this.source = source;

    final Map<String, Variant> properties = new HashMap<String, Variant> ();

    final HistoricalItemInformation information = new HistoricalItemInformation ( id, properties );
    this.item = new HSDBHistoricalItem ( executor, source, information );

    final Dictionary<String, Object> serviceProperties = new Hashtable<String, Object> ();
    serviceProperties.put ( Constants.SERVICE_PID, id );
    serviceProperties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );
    this.handle = context.registerService ( HistoricalItem.class, this.item, serviceProperties );
}
 
Example 20
Project: neoscada   File: StaticModbusExport.java   Source Code and License 5 votes vote down vote up
private StaticModbusExport ( final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ObjectPoolDataItemFactory itemFactory, final boolean disposeProcessor )
{
    super ( executor, processor, hiveSource, itemFactory );
    this.executor = executor;
    this.processor = processor;
    this.disposeProcessor = disposeProcessor;
}
 
Example 21
Project: lams   File: ThreadPoolTaskScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
	ScheduledExecutorService executor = getScheduledExecutor();
	try {
		return executor.scheduleWithFixedDelay(errorHandlingTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}
 
Example 22
Project: drift   File: TestDriftNettyMethodInvoker.java   Source Code and License 5 votes vote down vote up
@Test
public void testTimeout()
        throws Exception
{
    ScheduledExecutorService executor = newSingleThreadScheduledExecutor(daemonThreadsNamed("test-timeout"));

    DriftNettyMethodInvoker invoker = new DriftNettyMethodInvoker(
            new HangingConnectionManager(),
            executor,
            new Duration(20, MILLISECONDS));

    ListenableFuture<Object> response = invoker.invoke(new InvokeRequest(
            new MethodMetadata(
                    "test",
                    ImmutableList.of(),
                    (ThriftCodec<Object>) (Object) new VoidThriftCodec(),
                    ImmutableMap.of(),
                    false),
            () -> HostAndPort.fromParts("localhost", 1234),
            ImmutableMap.of(),
            ImmutableList.of()));

    try {
        response.get();
        fail("expected exception");
    }
    catch (ExecutionException e) {
        assertInstanceOf(e.getCause(), io.airlift.drift.TException.class);
        assertEquals(e.getCause().getMessage(), "Invocation response future did not complete after 20.00ms");
    }
    finally {
        executor.shutdown();
    }
}
 
Example 23
Project: GitHub   File: AnimationBackendDelegateWithInactivityCheck.java   Source Code and License 5 votes vote down vote up
public static <T extends AnimationBackend>
AnimationBackendDelegate<T> createForBackend(
    T backend,
    InactivityListener inactivityListener,
    MonotonicClock monotonicClock,
    ScheduledExecutorService scheduledExecutorServiceForUiThread) {
  return new AnimationBackendDelegateWithInactivityCheck<>(
      backend,
      inactivityListener,
      monotonicClock,
      scheduledExecutorServiceForUiThread);
}
 
Example 24
Project: GitHub   File: ExperimentalBitmapAnimationDrawableFactory.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 25
Project: ndbc   File: DataSourceTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void cancellation() throws CheckedFutureException {
  final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  try {
    final Future<Long> f = ds.execute("SELECT pg_sleep(999)");
    f.raise(new RuntimeException());
    f.get(timeout);
  } finally {
    scheduler.shutdown();
  }
}
 
Example 26
Project: jsf-core   File: RecorderSchedule.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    final RecorderSchedule s = new RecorderSchedule();
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("recoder"));
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                s.getDelaySecond();
            } catch (Exception e) {
                logger.error("RecoderSchedule error", e);
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
}
 
Example 27
Project: boohee_v5.6   File: NewThreadWorker.java   Source Code and License 5 votes vote down vote up
public static void registerExecutor(ScheduledThreadPoolExecutor service) {
    while (((ScheduledExecutorService) PURGE.get()) == null) {
        ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, new RxThreadFactory(PURGE_THREAD_PREFIX));
        if (PURGE.compareAndSet(null, exec)) {
            exec.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    NewThreadWorker.purgeExecutors();
                }
            }, (long) PURGE_FREQUENCY, (long) PURGE_FREQUENCY, TimeUnit.MILLISECONDS);
            break;
        }
        exec.shutdownNow();
    }
    EXECUTORS.putIfAbsent(service, service);
}
 
Example 28
Project: Re-Collector   File: ChunkReaderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void readPositionEnd() throws IOException, InterruptedException {
    final Utils.LogFile logFile = new Utils.LogFile(100 * 1024, 400, 100);
    logFile.close();
    final ArrayBlockingQueue<FileChunk> chunkQueue = Queues.newArrayBlockingQueue(1);
    final AsynchronousFileChannel channel = AsynchronousFileChannel.open(logFile.getPath(), StandardOpenOption.READ);
    final CountingAsyncFileChannel spy = new CountingAsyncFileChannel(channel);

    final ChunkReader chunkReader = new ChunkReader(mock(FileInput.class), logFile.getPath(), spy, chunkQueue, 10 * 1024,
            FileInput.InitialReadPosition.END, null);

    final ScheduledExecutorService chunkReaderExecutor = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder()
                    .setDaemon(false)
                    .setNameFormat("file-chunk-reader-%d")
                    .setUncaughtExceptionHandler(this)
                    .build()
    );

    final Thread consumer = new Thread() {
        @Override
        public void run() {
            try {
                final FileChunk chunk = chunkQueue.poll(2, TimeUnit.SECONDS);
                assertNull("Reading from the end of the file must not produce a chunk for a non-changing file.", chunk);
            } catch (InterruptedException ignore) {
            }
        }
    };
    consumer.start();
    chunkReaderExecutor.scheduleAtFixedRate(chunkReader, 0, 250, TimeUnit.MILLISECONDS);
    consumer.join();

    // we can process one chunk at a time, so one read is queued, the second is buffered
    assertEquals("The e should be empty", 1, chunkQueue.remainingCapacity());
}
 
Example 29
Project: Lagerta   File: Statistics.java   Source Code and License 5 votes vote down vote up
static void deployContinuously(Ignite ignite) {
    long reportFrequency = TestsHelper.getLoadTestsStatisticsReportFrequency();
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    final StatisticsDeploymentHelper helper = new StatisticsDeploymentHelper(ignite);

    executor.scheduleAtFixedRate(new Runnable() {
        @Override public void run() {
            helper.deployStatisticsCollector();
        }
    }, 0, reportFrequency, TimeUnit.MILLISECONDS);
}
 
Example 30
Project: sponge   File: SpongeUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Trial run of the engine. Shuts down after {@code timeout} seconds after startup.
 *
 * @param engine the engine.
 * @param timeout timeout in seconds.
 */
public static void trialRunEngine(Engine engine, int timeout) {
    final Semaphore semaphore = new Semaphore(0, true);

    // Startup the engine. After startup the engine runs on the threads other than the current one.
    engine.startup();

    try {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(() -> {
            // Release the semaphore after timeout.
            semaphore.release();
        }, timeout, TimeUnit.SECONDS);

        try {
            // Wait for releasing the semaphore after timeout.
            semaphore.acquire();
        } catch (InterruptedException e) {
            logger.warn("trialRunEngine", e);
        }

        executor.shutdown();
    } finally {
        // Shutdown the engine.
        engine.shutdown();
    }
}
 
Example 31
Project: factcast   File: FactsObserverFactory.java   Source Code and License 5 votes vote down vote up
@VisibleForTesting
FactsObserverFactory(@NonNull LinkFactory<FactsResource> factsResourceLinkFactory,
        @NonNull HyperSchemaCreator hyperSchemaCreator,
        @NonNull FactTransformer factTransformer,
        @NonNull ScheduledExecutorService executorService, int waitSecondsForCleanUpCheck) {
    this.factsResourceLinkFactory = factsResourceLinkFactory;
    this.hyperSchemaCreator = hyperSchemaCreator;
    this.factTransformer = factTransformer;
    this.executorService = executorService;
    this.waitSecondsForCleanUpCheck = waitSecondsForCleanUpCheck;
}
 
Example 32
Project: neoscada   File: HSDBStorageManager.java   Source Code and License 5 votes vote down vote up
public HSDBStorageManager ( final ScheduledExecutorService executor, final String prefix, final BundleContext bundleContext, final File root )
{
    this.executor = executor;
    this.prefix = prefix;
    this.root = root;
    this.context = bundleContext;

    scan ();
}
 
Example 33
Project: mug   File: Retryer.java   Source Code and License 5 votes vote down vote up
final void asynchronously(
    E event, Failable retry, ScheduledExecutorService executor, CompletableFuture<?> result) {
  beforeDelay(event);
  Failable afterDelay = () -> {
    afterDelay(event);
    retry.run();
  };
  ScheduledFuture<?> scheduled = executor.schedule(
      () -> afterDelay.run(result::completeExceptionally),
      duration().toMillis(), TimeUnit.MILLISECONDS);
  ifCancelled(result, canceled -> {scheduled.cancel(true);});
}
 
Example 34
Project: guava-mock   File: AbstractScheduledService.java   Source Code and License 5 votes vote down vote up
@Override
final Future<?> schedule(
    AbstractService service, ScheduledExecutorService executor, Runnable runnable) {
  ReschedulableCallable task = new ReschedulableCallable(service, executor, runnable);
  task.reschedule();
  return task;
}
 
Example 35
Project: lams   File: DefaultManagedTaskScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws NamingException {
	if (this.jndiName != null) {
		ScheduledExecutorService executor = this.jndiLocator.lookup(this.jndiName, ScheduledExecutorService.class);
		setConcurrentExecutor(executor);
		setScheduledExecutor(executor);
	}
}
 
Example 36
Project: LearningOfThinkInJava   File: ScheduledExecutorServiceDemo.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    ScheduledExecutorService ses= Executors.newScheduledThreadPool(10);
    ses.scheduleWithFixedDelay(new Runnable() {
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(System.currentTimeMillis()/1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    },0,2, TimeUnit.SECONDS);
}
 
Example 37
Project: JRediClients   File: RedissonBoundedBlockingQueueTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPollFromAny() throws InterruptedException {
    final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("queue:pollany");
    assertThat(queue1.trySetCapacity(10)).isTrue();
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.schedule(() -> {
        RBoundedBlockingQueue<Integer> queue2 = redisson.getBoundedBlockingQueue("queue:pollany1");
        assertThat(queue2.trySetCapacity(10)).isTrue();
        RBoundedBlockingQueue<Integer> queue3 = redisson.getBoundedBlockingQueue("queue:pollany2");
        assertThat(queue3.trySetCapacity(10)).isTrue();
        try {
            queue3.put(2);
            queue1.put(1);
            queue2.put(3);
        } catch (Exception e) {
            Assert.fail();
        }
    }, 3, TimeUnit.SECONDS);

    long s = System.currentTimeMillis();
    int l = queue1.pollFromAny(40, TimeUnit.SECONDS, "queue:pollany1", "queue:pollany2");

    Assert.assertEquals(2, l);
    Assert.assertTrue(System.currentTimeMillis() - s > 2000);
    
    executor.shutdown();
    assertThat(executor.awaitTermination(1, TimeUnit.MINUTES)).isTrue();
}
 
Example 38
Project: websiteMonitor   File: TabsTest.java   Source Code and License 5 votes vote down vote up
@Override
	public void start(Stage stage) throws Exception {
		BorderPane root = new BorderPane();
		JFXTabPane tabPane = new JFXTabPane();
		Tab tab1 = new Tab();
		tab1.setText("Graph Tab");
		Tab tab2 = new Tab();
		tab2.setText("Empty Tab");
		
		BorderPane gPane = new BorderPane();
		CategoryAxis x = new CategoryAxis();
		x.setLabel("Visited Sites");
		NumberAxis y = new NumberAxis();
		y.setLabel("Hits");
		lineChart = new LineChart<>(x, y);
		set2 = new XYChart.Series<>();
		set2.getData().add(new XYChart.Data("Ramzan",62));
//		set2.getData().add(new XYChart.Data("Hussan",421));
//		set2.getData().add(new XYChart.Data("Shoaib",92));
//		set2.getData().add(new XYChart.Data("Sudo",42));
		
		lineChart.setTitle("History Statistics");
		
		lineChart.getData().add(set2);
		JFXButton button = new JFXButton("add");
		button.addEventHandler(MouseEvent.MOUSE_CLICKED, e ->{
			set2.getData().remove(0);
			set2.getData().add(new XYChart.Data("chhala",45));
		});
		gPane.setCenter(lineChart);
		gPane.setLeft(button);
		
		tab1.setContent(gPane);
		tabPane.getTabs().addAll(tab1,tab2);
		
		root.setCenter(tabPane);
		Scene scene = new Scene(root,800,600);
		stage.setScene(scene);
		stage.show();
		
		final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
	    executorService.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				Random rand = new Random();
				System.out.println(set2.getData().size());
				java.util.Date date = new java.util.Date();
				SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
				set2.getData().add(new XYChart.Data(timeFormat.format(date),rand.nextInt(20)));	
			}
		}, 0, 1, TimeUnit.SECONDS);
	}
 
Example 39
Project: AthenaX   File: InstanceManager.java   Source Code and License 5 votes vote down vote up
@VisibleForTesting
public static InstanceManager create(
    AthenaXConfiguration conf,
    InstanceStateUpdateListener listener,
    ScheduledExecutorService executor) {
  HashMap<String, ClusterInfo> c = new HashMap<>();
  for (Map.Entry<String, AthenaXConfiguration.YarnCluster> e : conf.clusters().entrySet()) {
    ClusterInfo ci = new ClusterInfo(e.getKey(), e.getValue().toYarnClusterConfiguration());
    c.put(e.getKey(), ci);
  }
  return new InstanceManager(c, listener, executor, conf.getExtraConfLong(INSTANCE_MANAGER_RESCAN_INTERVAL));
}
 
Example 40
Project: AthenaX   File: JobDeployer.java   Source Code and License 5 votes vote down vote up
JobDeployer(YarnClusterConfiguration clusterConf, YarnClient yarnClient,
            ScheduledExecutorService executor, Configuration flinkConf) {
  this.clusterConf = clusterConf;
  this.executor = executor;
  this.flinkConf = flinkConf;
  this.yarnClient = yarnClient;
}
 
Example 41
Project: neoscada   File: BufferedDataSourceImpl.java   Source Code and License 5 votes vote down vote up
public BufferedDataSourceImpl ( final BundleContext context, final ScheduledExecutorService scheduler, final ObjectPoolTracker<DataSource> poolTracker, final DataNodeTracker dataNodeTracker, final String configurationId, final ObjectPoolImpl<BufferedDataSource> objectPool )
{
    this.context = context;
    this.scheduler = scheduler;
    this.poolTracker = poolTracker;
    this.dataNodeTracker = dataNodeTracker;
    this.configurationId = configurationId;
    this.objectPool = objectPool;
}
 
Example 42
Project: r2cloud   File: Util.java   Source Code and License 5 votes vote down vote up
public static void shutdown(ScheduledExecutorService executor, long timeoutMillis) {
	if (executor == null) {
		return;
	}
	executor.shutdownNow();
	boolean cleanlyTerminated;
	try {
		cleanlyTerminated = executor.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
		cleanlyTerminated = executor.isTerminated();
	}
	if (!cleanlyTerminated) {
		String threadpoolName;
		if (executor instanceof ScheduledThreadPoolExecutor) {
			ThreadFactory factory = ((ScheduledThreadPoolExecutor) executor).getThreadFactory();
			if (factory instanceof NamingThreadFactory) {
				NamingThreadFactory namingFactory = (NamingThreadFactory) factory;
				threadpoolName = namingFactory.getPrefix();
			} else {
				threadpoolName = "unknown[" + factory.getClass().getSimpleName() + "]";
			}
		} else {
			threadpoolName = "unknown[" + executor.getClass().getSimpleName() + "]";
		}
		LOG.error("executor did not terminate in the specified time: " + threadpoolName);
	}
}
 
Example 43
Project: iTAP-controller   File: SingletonTaskTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testConcurrentAddNoDelay() throws InterruptedException {
    ScheduledExecutorService ses =
        Executors.newSingleThreadScheduledExecutor();

    final Object tc = this;
    SingletonTask st1 = new SingletonTask(ses, new Runnable() {
        @Override
        public void run() {
            synchronized (tc) {
                ran += 1;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            synchronized (tc) {
                finished += 1;
                time = System.nanoTime();
            }
        }
    });

    st1.reschedule(0, null);
    Thread.sleep(20);
    assertEquals("Check that task started", 1, ran);
    assertEquals("Check that task not finished", 0, finished);
    st1.reschedule(0, null);
    assertTrue("Check task running state true", st1.context.taskRunning);
    assertTrue("Check task should run state true", st1.context.taskShouldRun);
    assertEquals("Check that task started", 1, ran);
    assertEquals("Check that task not finished", 0, finished);

    Thread.sleep(150);

    assertTrue("Check task running state false", !st1.context.taskRunning);
    assertTrue("Check task should run state false", !st1.context.taskShouldRun);
    assertEquals("Check that task ran exactly twice", 2, ran);
    assertEquals("Check that task finished exactly twice", 2, finished);

    ses.shutdown();
    ses.awaitTermination(5, TimeUnit.SECONDS);
}
 
Example 44
Project: elastic-apm-java-agent-poc   File: ApmAgent.java   Source Code and License 4 votes vote down vote up
public ScheduledExecutorService getTransactionsSender () {
  return transactionsSender;
}
 
Example 45
Project: neoscada   File: ModbusExport.java   Source Code and License 4 votes vote down vote up
public ModbusExport ( final String id, final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ManageableObjectPool<DataItem> itemObjectPool )
{
    this ( executor, processor, hiveSource, new ObjectPoolDataItemFactory ( executor, itemObjectPool, String.format ( "org.eclipse.scada.da.server.exporter.modbus.export.%s.information.", id ) ), "ModbusExporter/" + id ); //$NON-NLS-1$
}
 
Example 46
Project: future   File: Promise.java   Source Code and License 4 votes vote down vote up
@Override
public final Future<T> delayed(final Duration delay, final ScheduledExecutorService scheduler) {
  final DelayedPromise p = new DelayedPromise();
  scheduler.schedule(p, delay.toMillis(), TimeUnit.MILLISECONDS);
  return p;
}
 
Example 47
Project: googles-monorepo-demo   File: WrappingScheduledExecutorService.java   Source Code and License 4 votes vote down vote up
protected WrappingScheduledExecutorService(ScheduledExecutorService delegate) {
  super(delegate);
  this.delegate = delegate;
}
 
Example 48
Project: Reer   File: DaemonServices.java   Source Code and License 4 votes vote down vote up
protected DaemonHealthStats createDaemonHealthStats(DaemonRunningStats runningStats, ScheduledExecutorService scheduledExecutorService) {
    return new DaemonHealthStats(runningStats, scheduledExecutorService);
}
 
Example 49
Project: Nird2   File: TransportKeyManagerImplTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testKeysAreRotatedWhenAddingContact() throws Exception {
	Mockery context = new Mockery();
	final DatabaseComponent db = context.mock(DatabaseComponent.class);
	final CryptoComponent crypto = context.mock(CryptoComponent.class);
	final Executor dbExecutor = context.mock(Executor.class);
	final ScheduledExecutorService scheduler =
			context.mock(ScheduledExecutorService.class);
	final Clock clock = context.mock(Clock.class);

	final boolean alice = true;
	final TransportKeys transportKeys = createTransportKeys(999, 0);
	final TransportKeys rotated = createTransportKeys(1000, 0);
	final Transaction txn = new Transaction(null, false);

	context.checking(new Expectations() {{
		oneOf(crypto).deriveTransportKeys(transportId, masterKey, 999,
				alice);
		will(returnValue(transportKeys));
		// Get the current time (1 ms after start of rotation period 1000)
		oneOf(clock).currentTimeMillis();
		will(returnValue(rotationPeriodLength * 1000 + 1));
		// Rotate the transport keys
		oneOf(crypto).rotateTransportKeys(transportKeys, 1000);
		will(returnValue(rotated));
		// Encode the tags (3 sets)
		for (long i = 0; i < REORDERING_WINDOW_SIZE; i++) {
			exactly(3).of(crypto).encodeTag(with(any(byte[].class)),
					with(tagKey), with(i));
			will(new EncodeTagAction());
		}
		// Save the keys
		oneOf(db).addTransportKeys(txn, contactId, rotated);
	}});

	TransportKeyManager
			transportKeyManager = new TransportKeyManagerImpl(db,
			crypto, dbExecutor, scheduler, clock, transportId, maxLatency);
	// The timestamp is 1 ms before the start of rotation period 1000
	long timestamp = rotationPeriodLength * 1000 - 1;
	transportKeyManager.addContact(txn, contactId, masterKey, timestamp,
			alice);

	context.assertIsSatisfied();
}
 
Example 50
Project: monarch   File: PoolImpl.java   Source Code and License 4 votes vote down vote up
public ScheduledExecutorService getBackgroundProcessor() {
  return backgroundProcessor;
}
 
Example 51
Project: Nird2   File: TransportKeyManagerImplTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testKeysAreRotatedWhenAddingContact() throws Exception {
	Mockery context = new Mockery();
	final DatabaseComponent db = context.mock(DatabaseComponent.class);
	final CryptoComponent crypto = context.mock(CryptoComponent.class);
	final Executor dbExecutor = context.mock(Executor.class);
	final ScheduledExecutorService scheduler =
			context.mock(ScheduledExecutorService.class);
	final Clock clock = context.mock(Clock.class);

	final boolean alice = true;
	final TransportKeys transportKeys = createTransportKeys(999, 0);
	final TransportKeys rotated = createTransportKeys(1000, 0);
	final Transaction txn = new Transaction(null, false);

	context.checking(new Expectations() {{
		oneOf(crypto).deriveTransportKeys(transportId, masterKey, 999,
				alice);
		will(returnValue(transportKeys));
		// Get the current time (1 ms after start of rotation period 1000)
		oneOf(clock).currentTimeMillis();
		will(returnValue(rotationPeriodLength * 1000 + 1));
		// Rotate the transport keys
		oneOf(crypto).rotateTransportKeys(transportKeys, 1000);
		will(returnValue(rotated));
		// Encode the tags (3 sets)
		for (long i = 0; i < REORDERING_WINDOW_SIZE; i++) {
			exactly(3).of(crypto).encodeTag(with(any(byte[].class)),
					with(tagKey), with(i));
			will(new EncodeTagAction());
		}
		// Save the keys
		oneOf(db).addTransportKeys(txn, contactId, rotated);
	}});

	TransportKeyManager
			transportKeyManager = new TransportKeyManagerImpl(db,
			crypto, dbExecutor, scheduler, clock, transportId, maxLatency);
	// The timestamp is 1 ms before the start of rotation period 1000
	long timestamp = rotationPeriodLength * 1000 - 1;
	transportKeyManager.addContact(txn, contactId, masterKey, timestamp,
			alice);

	context.assertIsSatisfied();
}
 
Example 52
Project: letv   File: EnabledEventsStrategy.java   Source Code and License 4 votes vote down vote up
public EnabledEventsStrategy(Context context, ScheduledExecutorService executorService, EventsFilesManager<T> filesManager) {
    this.context = context;
    this.executorService = executorService;
    this.filesManager = filesManager;
    this.scheduledRolloverFutureRef = new AtomicReference();
}
 
Example 53
Project: yet-another-try   File: AsyncRetryExecutorBuilder.java   Source Code and License 4 votes vote down vote up
public ScheduledExecutorService timeoutExecutorService() {
  return timeoutExecutorService;
}
 
Example 54
Project: quickstart   File: AccessTokenRefresher.java   Source Code and License 4 votes vote down vote up
public static void schedule(AccessTokenProvider accessTokenProvider, long refreshAfterInSeconds) {
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  executor.scheduleAtFixedRate(accessTokenProvider::refreshToken, refreshAfterInSeconds - 2,
      refreshAfterInSeconds, TimeUnit.SECONDS);
}
 
Example 55
Project: Nird2   File: TransportKeyManagerImplTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testOutgoingStreamContextIsNullIfStreamCounterIsExhausted()
		throws Exception {
	Mockery context = new Mockery();
	final DatabaseComponent db = context.mock(DatabaseComponent.class);
	final CryptoComponent crypto = context.mock(CryptoComponent.class);
	final Executor dbExecutor = context.mock(Executor.class);
	final ScheduledExecutorService scheduler =
			context.mock(ScheduledExecutorService.class);
	final Clock clock = context.mock(Clock.class);

	final boolean alice = true;
	// The stream counter has been exhausted
	final TransportKeys transportKeys = createTransportKeys(1000,
			MAX_32_BIT_UNSIGNED + 1);
	final Transaction txn = new Transaction(null, false);

	context.checking(new Expectations() {{
		oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000,
				alice);
		will(returnValue(transportKeys));
		// Get the current time (the start of rotation period 1000)
		oneOf(clock).currentTimeMillis();
		will(returnValue(rotationPeriodLength * 1000));
		// Encode the tags (3 sets)
		for (long i = 0; i < REORDERING_WINDOW_SIZE; i++) {
			exactly(3).of(crypto).encodeTag(with(any(byte[].class)),
					with(tagKey), with(i));
			will(new EncodeTagAction());
		}
		// Rotate the transport keys (the keys are unaffected)
		oneOf(crypto).rotateTransportKeys(transportKeys, 1000);
		will(returnValue(transportKeys));
		// Save the keys
		oneOf(db).addTransportKeys(txn, contactId, transportKeys);
	}});

	TransportKeyManager
			transportKeyManager = new TransportKeyManagerImpl(db,
			crypto, dbExecutor, scheduler, clock, transportId, maxLatency);
	// The timestamp is at the start of rotation period 1000
	long timestamp = rotationPeriodLength * 1000;
	transportKeyManager.addContact(txn, contactId, masterKey, timestamp,
			alice);
	assertNull(transportKeyManager.getStreamContext(txn, contactId));

	context.assertIsSatisfied();
}
 
Example 56
Project: neoscada   File: MasterFactory.java   Source Code and License 4 votes vote down vote up
public MasterFactory ( final BundleContext context, final ScheduledExecutorService executor, final NioProcessor processor )
{
    super ( context, true );
    this.executor = executor;
    this.processor = processor;
}
 
Example 57
Project: firebase-admin-java   File: ConnectionContext.java   Source Code and License 4 votes vote down vote up
public ScheduledExecutorService getExecutorService() {
  return this.executorService;
}
 
Example 58
Project: neoscada   File: Hive.java   Source Code and License 4 votes vote down vote up
public ScheduledExecutorService getExecutor ()
{
    return this.executor;
}
 
Example 59
Project: firebase-admin-java   File: TestHelpers.java   Source Code and License 4 votes vote down vote up
public static ScheduledExecutorService getExecutorService(DatabaseConfig config) {
  DefaultRunLoop runLoop = (DefaultRunLoop) config.getRunLoop();
  return runLoop.getExecutorService();
}
 
Example 60
Project: boohee_v5.6   File: GenericScheduledExecutorService.java   Source Code and License 4 votes vote down vote up
public static ScheduledExecutorService getInstance() {
    return (ScheduledExecutorService) INSTANCE.executor.get();
}