示例#1
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);
      }
    }
  }
 void onActivity() {
   cancel();
   if (!inactivityTimer.isShutdown()) {
     try {
       inactivityFuture =
           inactivityTimer.schedule(
               new FinishListener(activity), INACTIVITY_DELAY_SECONDS, TimeUnit.SECONDS);
     } catch (RejectedExecutionException ree) {
       // surprising, but could be normal if for some reason the implementation just doesn't
       // think it can shcedule again. Since this time-out is non-essential, just forget it
     }
   }
 }
示例#3
0
 /** {@inheritDoc} */
 public ScheduledFuture<String> schedule(Command action, long delay, TimeUnit unit)
     throws RejectedExecutionException, NullPointerException {
   try {
     CallableActionWrapper task = new CallableActionWrapper(action);
     return mThreadPool.schedule(task, delay, unit);
   } catch (RejectedExecutionException e) {
     LOG.error("ActionBase.schedule()... RejectedExecutionException:" + e.getLocalizedMessage());
     throw e;
   } catch (NullPointerException e) {
     LOG.error("ActionBase.schedule()... Exception in schedule:" + e.getLocalizedMessage());
     throw e;
   }
 }
 public Future<Object> executeAsync(final ITemplate t) {
   final Future<Object> f = exec(null, t, null, null, null);
   // make sure it get cancelled if timeout
   scheduler.schedule(
       new Runnable() {
         @Override
         public void run() {
           f.cancel(true);
         }
       },
       timeout,
       TimeUnit.MILLISECONDS);
   return f;
 }
示例#5
0
  private void scheduleLedData(final int position, LedData data) {
    ledDataMap.put(position, data);
    thereIsNewData = true;

    if (data.duration > 0) {
      executorService.schedule(
          new Runnable() {
            @Override
            public void run() {
              scheduleLedData(position, new LedData());
            }
          },
          data.duration,
          TimeUnit.MILLISECONDS);
    }
  }
示例#6
0
 void scheduleReset(
     List<Integer> needsReset, AtomicIntegerArray oldUse, AtomicIntegerArray updated) {
   if (needsReset.size() == 0) return;
   executor.schedule(
       () -> {
         for (int i = 0; i < needsReset.size(); i++) {
           int index = needsReset.get(i);
           int value = oldUse.get(index);
           if (value == 0) {
             updated.set(index, 0);
             needsReset.remove(i--);
           }
         }
         scheduleReset(needsReset, oldUse, updated);
       },
       1,
       TimeUnit.MILLISECONDS);
 }
  /**
   * Sends a message.
   *
   * <p>Current thread is NOT blocked by this method call. But no two response-actions (onReceive or
   * onFail on any request) or response protocols will be executed at same time, so you can write
   * not thread-safe code inside them.
   *
   * <p>
   *
   * <p>This gets being very similar to automaton programming :)
   *
   * @param address receiver of message
   * @param message mail entry
   * @param type way of sending a message: TCP, single UPD...
   * @param timeout timeout in milliseconds
   * @param receiveListener an action to invoke when got an answer.
   * @param failListener an action to invoke when timeout exceeded.
   * @param <ReplyType> response message type
   */
  public <ReplyType extends ResponseMessage> void send(
      InetSocketAddress address,
      RequestMessage<ReplyType> message,
      DispatchType type,
      int timeout,
      ReceiveListener<ReplyType> receiveListener,
      FailListener failListener) {
    BlockingQueue<ResponseMessage> responseContainer = submit(address, message, type);

    // TODO: make in single thread
    scheduledExecutor.schedule(
        () -> {
          //noinspection unchecked
          ReplyType response = (ReplyType) responseContainer.poll();
          if (response != null) receiveListener.onReceive(address, response);
          else failListener.onFail(address);
        },
        timeout,
        TimeUnit.MILLISECONDS);
    // TODO: clear responseWaiters map
  }
 public void onActivity() {
   cancel();
   inactivityFuture =
       inactivityTimer.schedule(
           new FinishListener(activity), INACTIVITY_DELAY_SECONDS, TimeUnit.SECONDS);
 }
示例#9
0
 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
   return e.schedule(callable, delay, unit);
 }
示例#10
0
 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
   return e.schedule(command, delay, unit);
 }
 /**
  * Sends message to itself in specified delay.
  *
  * <p>Used to schedule some tasks and execute them sequentially with other response-actions.
  * Executed action must be specified as response protocol.
  *
  * @param message reminder message
  * @param delay when to send a mention
  */
 public void remind(ReminderMessage message, int delay) {
   Runnable remind =
       () -> send(null, message, DispatchType.LOOPBACK, 10000, (addr, response) -> {}, addr -> {});
   scheduledExecutor.schedule(remind, delay, TimeUnit.MILLISECONDS);
 }
  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);
    }
  }