private void cancel() {
   ScheduledFuture<?> future = inactivityFuture;
   if (future != null) {
     future.cancel(true);
     inactivityFuture = null;
   }
 }
 public void cancelApplicationThread(String applicationId) {
   ScheduledFuture scheduledFuture = threadHolderMap.get(applicationId);
   if (scheduledFuture != null) {
     scheduledFuture.cancel(true);
     threadHolderMap.remove(applicationId);
     urlResponseTimeCache.remove(applicationId);
   }
 }
  @Test
  public void testScheduleFixedRateCallable() throws Exception {
    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isZero();
    assertThat(duration.getCount()).isZero();

    assertThat(scheduledOnce.getCount()).isZero();
    assertThat(scheduledRepetitively.getCount()).isZero();
    assertThat(scheduledOverrun.getCount()).isZero();
    assertThat(percentOfPeriod.getCount()).isZero();

    ScheduledFuture<?> theFuture =
        instrumentedScheduledExecutor.scheduleAtFixedRate(
            new Runnable() {
              public void run() {
                assertThat(submitted.getCount()).isZero();

                assertThat(running.getCount()).isEqualTo(1);

                assertThat(scheduledOnce.getCount()).isEqualTo(0);
                assertThat(scheduledRepetitively.getCount()).isEqualTo(1);

                try {
                  TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException ex) {
                  Thread.currentThread().interrupt();
                }

                return;
              }
            },
            10L,
            10L,
            TimeUnit.MILLISECONDS);

    TimeUnit.MILLISECONDS.sleep(100);
    theFuture.cancel(true);
    TimeUnit.MILLISECONDS.sleep(100);

    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isNotEqualTo(0);
    assertThat(duration.getCount()).isNotEqualTo(0);
    assertThat(duration.getSnapshot().size()).isNotEqualTo(0);

    assertThat(scheduledOnce.getCount()).isZero();
    assertThat(scheduledRepetitively.getCount()).isEqualTo(1);
    assertThat(scheduledOverrun.getCount()).isNotEqualTo(0);
    assertThat(percentOfPeriod.getCount()).isNotEqualTo(0);
  }
  @Test
  public void testScheduleCallable() throws Exception {
    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isZero();
    assertThat(duration.getCount()).isZero();

    assertThat(scheduledOnce.getCount()).isZero();
    assertThat(scheduledRepetitively.getCount()).isZero();
    assertThat(scheduledOverrun.getCount()).isZero();
    assertThat(percentOfPeriod.getCount()).isZero();

    final Object obj = new Object();

    ScheduledFuture<Object> theFuture =
        instrumentedScheduledExecutor.schedule(
            new Callable<Object>() {
              public Object call() {
                assertThat(submitted.getCount()).isZero();

                assertThat(running.getCount()).isEqualTo(1);
                assertThat(completed.getCount()).isZero();
                assertThat(duration.getCount()).isZero();

                assertThat(scheduledOnce.getCount()).isEqualTo(1);
                assertThat(scheduledRepetitively.getCount()).isZero();
                assertThat(scheduledOverrun.getCount()).isZero();
                assertThat(percentOfPeriod.getCount()).isZero();

                return obj;
              }
            },
            10L,
            TimeUnit.MILLISECONDS);

    assertThat(theFuture.get()).isEqualTo(obj);

    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isEqualTo(1);
    assertThat(duration.getCount()).isEqualTo(1);
    assertThat(duration.getSnapshot().size()).isEqualTo(1);

    assertThat(scheduledOnce.getCount()).isEqualTo(1);
    assertThat(scheduledRepetitively.getCount()).isZero();
    assertThat(scheduledOverrun.getCount()).isZero();
    assertThat(percentOfPeriod.getCount()).isZero();
  }
 @Override
 public void destroy() {
   super.destroy();
   try {
     expireFuture.cancel(true);
   } catch (Throwable t) {
     LOGGER.warn(t.getMessage(), t);
   }
   try {
     for (Notifier notifier : notifiers.values()) {
       notifier.shutdown();
     }
   } catch (Throwable t) {
     LOGGER.warn(t.getMessage(), t);
   }
   for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
     JedisPool jedisPool = entry.getValue();
     try {
       jedisPool.destroy();
     } catch (Throwable t) {
       LOGGER.warn(
           "Failed to destroy the redis registry client. registry: "
               + entry.getKey()
               + ", cause: "
               + t.getMessage(),
           t);
     }
   }
 }
  @Test
  public void testScheduleRunnable() throws Exception {
    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isZero();
    assertThat(duration.getCount()).isZero();

    assertThat(scheduledOnce.getCount()).isZero();
    assertThat(scheduledRepetitively.getCount()).isZero();
    assertThat(scheduledOverrun.getCount()).isZero();
    assertThat(percentOfPeriod.getCount()).isZero();

    ScheduledFuture<?> theFuture =
        instrumentedScheduledExecutor.schedule(
            new Runnable() {
              public void run() {
                assertThat(submitted.getCount()).isZero();

                assertThat(running.getCount()).isEqualTo(1);
                assertThat(completed.getCount()).isZero();
                assertThat(duration.getCount()).isZero();

                assertThat(scheduledOnce.getCount()).isEqualTo(1);
                assertThat(scheduledRepetitively.getCount()).isZero();
                assertThat(scheduledOverrun.getCount()).isZero();
                assertThat(percentOfPeriod.getCount()).isZero();
              }
            },
            10L,
            TimeUnit.MILLISECONDS);

    theFuture.get();

    assertThat(submitted.getCount()).isZero();

    assertThat(running.getCount()).isZero();
    assertThat(completed.getCount()).isEqualTo(1);
    assertThat(duration.getCount()).isEqualTo(1);
    assertThat(duration.getSnapshot().size()).isEqualTo(1);

    assertThat(scheduledOnce.getCount()).isEqualTo(1);
    assertThat(scheduledRepetitively.getCount()).isZero();
    assertThat(scheduledOverrun.getCount()).isZero();
    assertThat(percentOfPeriod.getCount()).isZero();
  }
Пример #7
0
 private void shutdownSamp() {
   sampMonitorHandle.cancel(true);
   sampClient.setActive(false);
   sampClient = null;
   if (hub != null) {
     hub.shutdown();
   }
 }
Пример #8
0
 private void cancelNotificationUpdater() {
   boolean result = false;
   if (notificationUpdaterFuture != null) {
     result = notificationUpdaterFuture.cancel(true);
   }
   notificationUpdater = null;
   notificationUpdaterFuture = null;
   Log.d(TAG, "NotificationUpdater cancelled. Result: " + result);
 }
Пример #9
0
  private void fixTimeLimit() {
    if (timeLimitFuture != null) timeLimitFuture.cancel(true);

    if (running && limits.containsKey(TIMER_COUNTER)) {
      long delay = limits.get(TIMER_COUNTER) * 1000 - time;
      if (delay > 0) {
        timeLimitFuture = scheduler.schedule(new TimeLimitTask(), delay, TimeUnit.MILLISECONDS);
      }
    }
  }
  public void testDelayedTasksReusePooledThreadIfExecuteAtDifferentTimes()
      throws InterruptedException, ExecutionException {
    final AppScheduledExecutorService service = new AppScheduledExecutorService(getName());
    final List<LogInfo> log = Collections.synchronizedList(new ArrayList<>());
    // pre-start one thread
    Future<?> future = service.submit(EmptyRunnable.getInstance());
    future.get();
    service.setBackendPoolCorePoolSize(1);
    assertEquals(1, service.getBackendPoolExecutorSize());

    int delay = 500;

    ScheduledFuture<?> f1 =
        service.schedule((Runnable) () -> log.add(new LogInfo(1)), delay, TimeUnit.MILLISECONDS);
    ScheduledFuture<?> f2 =
        service.schedule(
            (Runnable) () -> log.add(new LogInfo(2)), delay + 100, TimeUnit.MILLISECONDS);
    ScheduledFuture<?> f3 =
        service.schedule(
            (Runnable) () -> log.add(new LogInfo(3)), delay + 200, TimeUnit.MILLISECONDS);

    assertEquals(1, service.getBackendPoolExecutorSize());

    assertFalse(f1.isDone());
    assertFalse(f2.isDone());
    assertFalse(f3.isDone());

    TimeoutUtil.sleep(delay + 200 + 300);
    assertTrue(f1.isDone());
    assertTrue(f2.isDone());
    assertTrue(f3.isDone());
    assertEquals(1, service.getBackendPoolExecutorSize());

    assertEquals(3, log.size());
    Set<Thread> usedThreads =
        new HashSet<>(
            Arrays.asList(
                log.get(0).currentThread, log.get(1).currentThread, log.get(2).currentThread));
    if (usedThreads.size() != 1) {
      System.err.println(ThreadDumper.dumpThreadsToString());
    }
    assertEquals(usedThreads.toString(), 1, usedThreads.size()); // must be executed in same thread

    service.shutdownAppScheduledExecutorService();
    assertTrue(service.awaitTermination(10, TimeUnit.SECONDS));
  }
Пример #11
0
  private void onPreStopExecution(TestExecution execution) {
    log.debug("Pre-stopping canvas {}", getLabel());
    hasStarted = false;
    if (timeLimitFuture != null) timeLimitFuture.cancel(true);

    if (isAbortOnFinish()) {
      log.debug("Cancelling all components running on {}", this);
      cancelComponents();
    } else {
      log.debug("Waiting for all components to complete on {}", this);
      waitForComponentsToComplete();
    }
    log.debug("Calling onComplete on execution canvas");
    onComplete(execution.getCanvas());
  }
Пример #12
0
 synchronized void stop() {
   if (isRunning()) {
     ticker.cancel(true); // may interrupt if running
     ticker = null;
   }
   // let any threads waiting on the clock fall through
   synchronized (ticks) {
     // one should be sufficient but this is to be safe
     for (int i = 0; i < 5; i++) {
       ticks.notifyAll();
       try {
         Thread.sleep(10);
       } catch (InterruptedException ignored) {
       }
     }
   }
 }
Пример #13
0
 private void cancel() {
   if (inactivityFuture != null) {
     inactivityFuture.cancel(true);
     inactivityFuture = null;
   }
 }
Пример #14
0
 public boolean isEnabled() {
   return !scheduledGossipTask.isCancelled();
 }
Пример #15
0
 public void stop() {
   scheduledGossipTask.cancel(false);
 }
Пример #16
0
 public void stopDaemon() {
   scheduledTask.cancel(true);
   scheduler.shutdownNow();
 }
Пример #17
0
 public synchronized boolean isPaused() {
   return !executor.isShutdown() && (ticker == null || ticker.isCancelled());
 }
Пример #18
0
  @Override
  public String getStatus() {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    if (executor == null) {
      out.println("Jobs execution pool:");
      out.println("~~~~~~~~~~~~~~~~~~~");
      out.println("(not yet started)");
      return sw.toString();
    }
    out.println("Jobs execution pool:");
    out.println("~~~~~~~~~~~~~~~~~~~");
    out.println("Pool size: " + executor.getPoolSize());
    out.println("Active count: " + executor.getActiveCount());
    out.println("Scheduled task count: " + executor.getTaskCount());
    out.println("Queue size: " + executor.getQueue().size());
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    if (!scheduledJobs.isEmpty()) {
      out.println();
      out.println("Scheduled jobs (" + scheduledJobs.size() + "):");
      out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~");
      for (Job job : scheduledJobs) {
        out.print(job.getClass().getName());
        if (job.getClass().isAnnotationPresent(OnApplicationStart.class)
            && !(job.getClass().isAnnotationPresent(On.class)
                || job.getClass().isAnnotationPresent(Every.class))) {
          OnApplicationStart appStartAnnotation =
              job.getClass().getAnnotation(OnApplicationStart.class);
          out.print(
              " run at application start" + (appStartAnnotation.async() ? " (async)" : "") + ".");
        }

        if (job.getClass().isAnnotationPresent(On.class)) {

          String cron = job.getClass().getAnnotation(On.class).value();
          if (cron != null && cron.startsWith("cron.")) {
            cron = Play.configuration.getProperty(cron);
          }
          out.print(" run with cron expression " + cron + ".");
        }
        if (job.getClass().isAnnotationPresent(Every.class)) {
          out.print(" run every " + job.getClass().getAnnotation(Every.class).value() + ".");
        }
        if (job.lastRun > 0) {
          out.print(" (last run at " + df.format(new Date(job.lastRun)));
          if (job.wasError) {
            out.print(" with error)");
          } else {
            out.print(")");
          }
        } else {
          out.print(" (has never run)");
        }
        out.println();
      }
    }
    if (!executor.getQueue().isEmpty()) {
      out.println();
      out.println("Waiting jobs:");
      out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");
      ScheduledFuture[] q = executor.getQueue().toArray(new ScheduledFuture[0]);

      for (int i = 0; i < q.length; i++) {
        ScheduledFuture task = q[i];
        out.println(
            Java.extractUnderlyingCallable((FutureTask<?>) task)
                + " will run in "
                + task.getDelay(TimeUnit.SECONDS)
                + " seconds");
      }
    }
    return sw.toString();
  }
 @Override
 public boolean isDone() {
   return scheduledFuture.isDone();
 }
Пример #20
0
  public static void main(String args[]) {
    String worldName = System.getProperty("multiverse.worldname");
    Properties properties = InitLogAndPid.initLogAndPid(args, worldName, null);

    System.err.println("Multiverse server version " + ServerVersion.getVersionString());

    List<String> agentNames = new LinkedList<String>();

    LongOpt[] longopts = new LongOpt[2];
    longopts[0] = new LongOpt("pid", LongOpt.REQUIRED_ARGUMENT, null, 2);
    longopts[1] = new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 3);
    Getopt opt = new Getopt("DomainServer", args, "a:m:t:p:P:", longopts);
    int c;
    int port = DEFAULT_PORT;

    String portStr = properties.getProperty("multiverse.msgsvr_port");
    if (portStr != null) port = Integer.parseInt(portStr);

    PluginStartGroup pluginStartGroup = new PluginStartGroup();

    while ((c = opt.getopt()) != -1) {
      switch (c) {
        case 'a':
          agentNames.add(opt.getOptarg());
          break;
        case 't':
        case 'm':
          // ignore RuntimeMarshalling flags
          opt.getOptarg();
          break;
        case 'p':
          String pluginSpec = opt.getOptarg();
          String[] pluginDef = pluginSpec.split(",", 2);
          if (pluginDef.length != 2) {
            System.err.println("Invalid plugin spec format: " + pluginSpec);
            Log.error("Invalid plugin spec format: " + pluginSpec);
            System.exit(1);
          }
          int expected = Integer.parseInt(pluginDef[1]);
          pluginStartGroup.add(pluginDef[0], expected);
          break;
        case '?':
          System.exit(1);
          break;
        case 'P':
          break;
        case 2:
          // ignore --pid
          opt.getOptarg();
          break;
          // port
        case 3:
          String arg = opt.getOptarg();
          port = Integer.parseInt(arg);
          break;
        default:
          break;
      }
    }

    String svrName = System.getProperty("multiverse.loggername");
    String runDir = System.getProperty("multiverse.rundir");

    // Windows non-Cygwin only - save process ID for status script
    if (System.getProperty("os.name").contains("Windows") && svrName != null && runDir != null) {
      saveProcessID(svrName, runDir);
    }

    // parse command-line options

    domainServer = new DomainServer(port);
    domainServer.setAgentNames(agentNames);
    domainServer.setWorldName(worldName);
    domainServer.start();

    pluginStartGroup.prepareDependencies(properties, worldName);
    domainServer.addPluginStartGroup(pluginStartGroup);
    pluginStartGroup.pluginAvailable("Domain", "Domain");

    String timeoutStr = properties.getProperty("multiverse.startup_timeout");
    int timeout = 120;
    if (timeoutStr != null) {
      timeout = Integer.parseInt(timeoutStr);
    }

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> timeoutHandler =
        scheduler.schedule(new TimeoutRunnable(timeout), timeout, TimeUnit.SECONDS);

    javax.crypto.SecretKey domainKey = SecureTokenUtil.generateDomainKey();
    // XXX Use a random keyID for now. Ideally, this would be semi-unique.
    long keyId = new Random().nextLong();
    encodedDomainKey = Base64.encodeBytes(SecureTokenUtil.encodeDomainKey(keyId, domainKey));
    Log.debug("generated domain key: " + encodedDomainKey);

    try {
      pluginStartGroup.awaitDependency("Domain");
      timeoutHandler.cancel(false);
      String availableMessage = properties.getProperty("multiverse.world_available_message");
      String availableFile = properties.getProperty("multiverse.world_available_file");
      if (availableFile != null) touchFile(FileUtil.expandFileName(availableFile));
      if (availableMessage != null) System.err.println("\n" + availableMessage);
      while (true) {
        Thread.sleep(10000000);
      }
    } catch (Exception ex) {
      Log.exception("DomainServer.main", ex);
    }
  }
 @Override
 public boolean cancel(boolean mayInterruptIfRunning) {
   futures.remove(scheduledFuture);
   return scheduledFuture.cancel(mayInterruptIfRunning);
 }
Пример #22
0
 private void shutdownSherpa() {
   sherpaMonitorHandle.cancel(true);
 }
Пример #23
0
 private void onStopExecution() {
   log.debug("Stopping canvas {}", getLabel());
   if (timerFuture != null) timerFuture.cancel(true);
   setRunning(false);
 }
Пример #24
0
 public synchronized boolean isRunning() {
   return !executor.isShutdown() && ticker != null && !ticker.isCancelled();
 }
 @Override
 public boolean isCancelled() {
   return scheduledFuture.isCancelled();
 }
  public void testDelayedWorks() throws InterruptedException {
    final AppScheduledExecutorService service = new AppScheduledExecutorService(getName());
    final List<LogInfo> log = Collections.synchronizedList(new ArrayList<>());
    assertFalse(service.isShutdown());
    assertFalse(service.isTerminated());

    service.invokeAll(
        Collections.nCopies(
            service.getBackendPoolCorePoolSize() + 1,
            Executors.callable(EmptyRunnable.getInstance()))); // pre-start all threads

    int delay = 1000;
    long start = System.currentTimeMillis();
    ScheduledFuture<?> f1 =
        service.schedule(
            () -> {
              log.add(new LogInfo(1));
              TimeoutUtil.sleep(10);
            },
            delay,
            TimeUnit.MILLISECONDS);
    assertFalse(service.isShutdown());
    assertFalse(service.isTerminated());
    ScheduledFuture<?> f2 =
        service.schedule(
            () -> {
              log.add(new LogInfo(2));
              TimeoutUtil.sleep(10);
            },
            delay,
            TimeUnit.MILLISECONDS);
    assertFalse(service.isShutdown());
    assertFalse(service.isTerminated());
    ScheduledFuture<?> f3 =
        service.schedule(
            () -> {
              log.add(new LogInfo(3));
              TimeoutUtil.sleep(10);
            },
            delay,
            TimeUnit.MILLISECONDS);

    assertFalse(service.isShutdown());
    assertFalse(service.isTerminated());
    Future<?> f4 = service.submit((Runnable) () -> log.add(new LogInfo(4)));

    assertFalse(service.isShutdown());
    assertFalse(service.isTerminated());
    assertFalse(f1.isDone());
    assertFalse(f2.isDone());
    assertFalse(f3.isDone());

    TimeoutUtil.sleep(delay / 2);
    long elapsed = System.currentTimeMillis() - start; // can be > delay/2 on overloaded agent
    assertEquals(String.valueOf(f1.isDone()), elapsed > delay, f1.isDone());
    assertEquals(String.valueOf(f2.isDone()), elapsed > delay, f2.isDone());
    assertEquals(String.valueOf(f3.isDone()), elapsed > delay, f3.isDone());
    assertTrue(f4.isDone());

    TimeoutUtil.sleep(delay / 2 + 500);
    assertTrue(f1.isDone());
    assertTrue(f2.isDone());
    assertTrue(f3.isDone());
    assertTrue(f4.isDone());

    assertEquals(4, log.size());
    assertEquals(4, log.get(0).runnable);
    List<Thread> threads =
        Arrays.asList(log.get(1).currentThread, log.get(2).currentThread, log.get(3).currentThread);
    assertEquals(
        threads.toString(), 3, new HashSet<>(threads).size()); // must be executed in parallel

    service.shutdownAppScheduledExecutorService();
    assertTrue(service.awaitTermination(10, TimeUnit.SECONDS));
  }