/**
   * This method follow the next steps:
   *
   * <ul>
   *   <li>Launch each action with his delay.
   *   <li>After the longest delay action get into next state.
   *   <li>Return the next state.
   * </ul>
   *
   * @see com.yerbamateprimer.round.state.exit.StateExit#apply()
   */
  @Override
  public State apply() {
    for (Entry<Long, Collection<SystemAction>> delayedActions : getGetOutActions().entrySet()) {
      Long delay = delayedActions.getKey();
      final Collection<SystemAction> actions = delayedActions.getValue();

      LOGGER.debug("The actions {} will be executed after {} millis, from now.", actions, delay);
      Runnable executeActions =
          new Runnable() {
            public void run() {
              for (SystemAction action : actions) {
                action.execute();
              }
            }
          };
      EXECUTOR.schedule(executeActions, delay, TimeUnit.MILLISECONDS);
    }
    Long getInDelay = getGetOutActions().keySet().iterator().next();

    Runnable executeGetIn =
        new Runnable() {
          public void run() {
            getNextState().getIn();
          }
        };
    EXECUTOR.schedule(executeGetIn, getInDelay, TimeUnit.MILLISECONDS);

    return getNextState();
  }
Example #2
0
  private void createTimeoutTasks(final Thread t) {
    scenarioTimeoutInterrupt =
        timeoutExcecutor.schedule(
            new Runnable() {
              public void run() {
                timeoutIfStillRunning(t);
              }
            },
            scenarioTimeoutMillis,
            TimeUnit.MILLISECONDS);

    scenarioTimeoutStopThread =
        timeoutExcecutor.schedule(
            new Runnable() {
              public void run() {
                stopThreadIfStillRunning(t);
              }
            },
            scenarioTimeoutMillis * 2,
            TimeUnit.MILLISECONDS);

    scenarioTimeoutKill =
        timeoutExcecutor.schedule(
            new Runnable() {
              public void run() {
                killInterpreterIfStillRunning(t);
              }
            },
            scenarioTimeoutMillis * 3,
            TimeUnit.MILLISECONDS);
  }
Example #3
0
 public void interrupt(boolean state, Duration duration) {
   if (interrupted) {
     interruptingStopEvent.cancel(true);
   } else {
     interrupted = true;
   }
   scheduler.schedule(new SchedulerEvent(state), 0, SECONDS);
   scheduler.schedule(new SchedulerEvent(currentState), duration.getSeconds(), SECONDS);
 }
  private void startUpdating(final View v) {

    if (mUpdater != null) {
      return;
    }
    mHandler =
        new Handler() {

          @Override
          public void handleMessage(Message msg) {

            int tagId = 0;
            if (v != null && v.getTag() != null) {
              tagId = Integer.parseInt(v.getTag().toString());
            }

            switch (tagId) {
              case 1:
                selectDeSelectState(v, true, true);
                break;

              case 2:
                selectDeSelectState(v, true, false);
                break;
            }
            super.handleMessage(msg);
          }
        };
    mUpdater = Executors.newSingleThreadScheduledExecutor();
    mUpdater.schedule(new UpdateCounterTask(), 200, TimeUnit.MILLISECONDS);
  }
  public static void main(String[] args) {
    /** 使用工厂方法初始化一个ScheduledThreadPool */
    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(2);

    TimerTask task1 =
        new TimerTask() {
          @Override
          public void run() {
            try {
              System.out.println("task1 invoked ! " + (System.currentTimeMillis() - start));
              Thread.sleep(3000);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    TimerTask task2 =
        new TimerTask() {
          @Override
          public void run() {
            System.out.println("task2 invoked ! " + (System.currentTimeMillis() - start));
          }
        };
    start = System.currentTimeMillis();
    newScheduledThreadPool.schedule(task1, 1000, TimeUnit.MILLISECONDS);
    newScheduledThreadPool.schedule(task2, 3000, TimeUnit.MILLISECONDS);
  }
 public static void main(String[] args) throws InterruptedException, ExecutionException {
   // *1
   ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
   // *2
   Runnable task1 =
       new Runnable() {
         public void run() {
           System.out.println("Taskrepeating.");
         }
       };
   // *3 每隔5秒执行一次
   final ScheduledFuture future1 = service.scheduleAtFixedRate(task1, 0, 1, TimeUnit.SECONDS);
   // *4
   ScheduledFuture future2 =
       service.schedule(
           new Callable() {
             public String call() {
               future1.cancel(true);
               return "taskcancelled!";
             }
           },
           10,
           TimeUnit.SECONDS);
   System.out.println(future2.get());
   // *5
   service.shutdown();
 }
Example #7
0
 @Override
 public void onAutoFailover(Runnable runnable) {
   executorService.schedule(
       runnable,
       leadingOptions.leadingTimeLimit.getValue(),
       leadingOptions.leadingTimeLimit.getUnit().getTimeUnit());
 }
Example #8
0
 @Override
 public <V> ListenableScheduledFuture<V> schedule(
     Callable<V> callable, long delay, TimeUnit unit) {
   TrustedListenableFutureTask<V> task = TrustedListenableFutureTask.create(callable);
   ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit);
   return new ListenableScheduledTask<V>(task, scheduled);
 }
  /**
   * Tests that a partition with expired connections should those connections killed off.
   *
   * @throws SQLException
   */
  @Test
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void testConnectionExpired() throws SQLException {

    TransferQueue<ConnectionHandle> mockQueue = createNiceMock(TransferQueue.class);
    expect(mockConnectionPartition.getAvailableConnections()).andReturn(1);
    expect(mockConnectionPartition.getFreeConnections()).andReturn(mockQueue).anyTimes();
    ConnectionHandle mockConnectionExpired = createNiceMock(ConnectionHandle.class);
    ConnectionHandle mockConnection = createNiceMock(ConnectionHandle.class);
    expect(mockQueue.poll()).andReturn(mockConnectionExpired).once();

    expect(mockConnectionExpired.isExpired(anyLong())).andReturn(true).once();

    expect(mockExecutor.isShutdown()).andReturn(false).once();

    mockConnectionExpired.internalClose();
    expectLastCall().once();

    mockPool.postDestroyConnection(mockConnectionExpired);
    expectLastCall().once();

    expect(mockExecutor.schedule((Callable) anyObject(), anyLong(), (TimeUnit) anyObject()))
        .andReturn(null)
        .once();
    replay(
        mockQueue,
        mockExecutor,
        mockConnectionPartition,
        mockConnection,
        mockPool,
        mockConnectionExpired);
    testClass.run();
    verify(mockConnectionExpired);
  }
 @Override
 public void propose(final PaxosMessage proposal) {
   sendAllMessage(proposal);
   Runnable rePropose =
       new Runnable() {
         @Override
         public void run() {
           long timeToSleep = 1000;
           while (chosen.get(proposal.getInstanceNum()) == null) {
             try {
               Thread.sleep(timeToSleep);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
             sendAllMessage(proposal);
             timeToSleep =
                 timeToSleep * 2 < 60 * 1000
                     ? timeToSleep * 2
                     : 60
                         * 1000; // Increase wait time up to a minute (helps prevent spamming in
                                 // the logs >.>)
           }
           System.out.println("Chose: " + proposal);
         }
       };
   scheduler.schedule(rePropose, 1, TimeUnit.SECONDS);
 }
  /**
   * Build a new end user instance from a JSONObject description
   *
   * @param jsonObject the JSONObject description
   */
  public AppsgateEndUser(JSONObject jsonObject) {

    this.instanciationService = Executors.newScheduledThreadPool(1);

    try {
      this.id = jsonObject.getString("id");
      this.hashPSWD = jsonObject.getString("hashPSWD");
      this.lastName = jsonObject.getString("lastName");
      this.firstName = jsonObject.getString("firstName");
      this.role = jsonObject.getString("role");

      JSONArray devices = jsonObject.getJSONArray("devices");
      int size = devices.length();
      int i = 0;
      while (i < size) {
        deviceOwnedList.add(devices.getString(i));
        i++;
      }

      // Create thread that take the account list in parameter and instanciate all account
      // TODO Schedule instanciation to avoid dependency collision
      instanciationService.schedule(
          new accountInstanciation(jsonObject.getJSONArray("accounts")), 15, TimeUnit.SECONDS);

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  /**
   * Submits or schedules an {@link ApplicationTask} on the the shared executor service.
   *
   * @param task The task
   * @param delay Initial delay in milliseconds, or zero for ASAP
   * @param repeatEvery Repeat delay in milliseconds, or zero for no repetition
   * @param fixedRepeat Whether repetitions are at fixed times, or if the repeat delay begins when
   *     the task ends
   * @return A future for the task
   */
  private <T> Future<T> task(
      ApplicationTask<T> task, int delay, int repeatEvery, boolean fixedRepeat) {
    ExecutorService executor = getExecutor();
    if ((delay > 0) || (repeatEvery > 0)) {
      if (!(executor instanceof ScheduledExecutorService))
        throw new RuntimeException(
            "Executor must implement the ScheduledExecutorService interface to allow for delayed tasks");

      ScheduledExecutorService scheduledExecutor = (ScheduledExecutorService) executor;
      if (repeatEvery > 0) {
        if (fixedRepeat) {
          @SuppressWarnings("unchecked")
          ScheduledFuture<T> future =
              (ScheduledFuture<T>)
                  scheduledExecutor.scheduleAtFixedRate(
                      task, delay, repeatEvery, TimeUnit.MILLISECONDS);
          return future;
        } else {
          @SuppressWarnings("unchecked")
          ScheduledFuture<T> future =
              (ScheduledFuture<T>)
                  scheduledExecutor.scheduleWithFixedDelay(
                      task, delay, repeatEvery, TimeUnit.MILLISECONDS);
          return future;
        }
      } else return scheduledExecutor.schedule((Callable<T>) task, delay, TimeUnit.MILLISECONDS);
    } else return executor.submit((Callable<T>) task);
  }
 private void doHttpMaxFailover() {
   long maxTimeAgo = clock.now() - silentPeriodForMaxHttpRequest;
   if (!httpRequestControl.requestQueued(HttpRequestControl.RequestReason.MAX)
       && UpdateSettings.LAST_SIMPP_FAILOVER.getValue() < maxTimeAgo) {
     int rndDelay = RANDOM.nextInt(maxMaxHttpRequestDelay) + minMaxHttpRequestDelay;
     final String rndUri = maxedUpdateList.get(RANDOM.nextInt(maxedUpdateList.size()));
     LOG.debug("Scheduling http max failover in: " + rndDelay + ", to: " + rndUri);
     backgroundExecutor.schedule(
         new Runnable() {
           public void run() {
             String url = rndUri;
             try {
               launchHTTPUpdate(url);
             } catch (URISyntaxException e) {
               httpRequestControl.requestFinished();
               httpRequestControl.cancelRequest();
               LOG.warn("uri failure", e);
             }
           }
         },
         rndDelay,
         TimeUnit.MILLISECONDS);
   } else {
     LOG.debug("Ignoring http max failover.");
   }
 }
 private Capture<Runnable> expectOfferDeclineIn(int delayMillis) {
   expect(returnDelay.get()).andReturn(Amount.of(delayMillis, Time.MILLISECONDS));
   Capture<Runnable> runnable = createCapture();
   executor.schedule(capture(runnable), eq((long) delayMillis), eq(TimeUnit.MILLISECONDS));
   expectLastCall().andReturn(createMock(ScheduledFuture.class));
   return runnable;
 }
Example #15
0
  protected void showErrorDialog(View view, boolean cancelable) {
    if (getActivity().isFinishing()) return;

    if (mErrorDialog == null) {
      mErrorDialog = new AlertDialog.Builder(mContext, R.style.error_dialog).create();
      mErrorDialog.setCancelable(cancelable);
      mErrorDialog.setCanceledOnTouchOutside(cancelable);
    }
    mErrorDialog.show();
    Window window = mErrorDialog.getWindow();
    window.setGravity(Gravity.CENTER | Gravity.BOTTOM);
    window.setContentView(view);
    window.setWindowAnimations(R.style.animation_error_dialog);
    int width = (int) (ScreenUtils.getScreenW(mContext) * 5 / 6f);
    WindowManager.LayoutParams wmlp = window.getAttributes();
    wmlp.gravity = Gravity.CENTER | Gravity.BOTTOM;
    wmlp.y = 200;
    window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

    executor.schedule(
        new Runnable() {
          @Override
          public void run() {
            dismissErrorDialog();
          }
        },
        5,
        TimeUnit.SECONDS);
  }
 public static void handleDelayWithTimer(Runnable r) {
   if (delay > 0) {
     timerPool.schedule(r, delay, TimeUnit.MILLISECONDS);
   } else {
     r.run();
   }
 }
Example #17
0
    GuardTask(final InetSocketAddress addr) throws IOException {
      if (bindDelay > 0) {
        logger.info("Socket binding will be delayed by {}ms...", bindDelay);
      }

      Runnable task =
          new Runnable() {
            @Override
            public void run() {
              try {
                logger.debug("Binding {} after delaying {}ms...", addr, bindDelay);
                final ServerSocketChannel ssc = ServerSocketChannel.open();
                ssc.configureBlocking(false);
                serverSocket = ssc.socket();
                serverSocket.bind(addr);

                selector = Selector.open();
                ssc.register(selector, SelectionKey.OP_ACCEPT, addr);
                logger.info("Open server socket {} ", serverSocket);
              } catch (IOException e) {
                throw new RuntimeException(e);
              }
            }
          };
      binder.schedule(task, bindDelay, TimeUnit.MILLISECONDS);
    }
  @triggeredBy({DEFINED_BY, MIRRORED_BY, SERVICED_BY})
  public void definitionChanged() throws Exception {
    ObjectConnection active = getObjectConnection();
    final Logger logger = LoggerFactory.getLogger(DomainSupport.class);
    final ObjectRepository repository = active.getRepository();
    final Resource resource = getResource();
    executor.schedule(
        new Runnable() {
          public String toString() {
            return "refresh " + resource;
          }

          public void run() {
            try {
              logger.info("Refreshing {}", resource);
              ObjectConnection con = repository.getConnection();
              try {
                Domain domain = con.getObject(Domain.class, resource);
                domain.refreshGraphs();
              } finally {
                con.close();
              }
            } catch (Exception e) {
              logger.warn("Could not refresh " + resource, e);
              executor.schedule(this, 5, TimeUnit.MINUTES);
            }
          }
        },
        30,
        TimeUnit.SECONDS);
  }
  public static void main(String[] args) {

    ScheduledExecutorService service = Executors.newScheduledThreadPool(2);

    service.scheduleAtFixedRate(
        new Runnable() {

          @Override
          public void run() {
            System.out.println("haha");
          }
        },
        0,
        1,
        TimeUnit.SECONDS);

    service.schedule(
        new Runnable() {

          @Override
          public void run() {
            System.out.println("!!!!!!!!!!");
          }
        },
        10,
        TimeUnit.SECONDS);
  }
Example #20
0
 public ChannelListener(
     final int threadPoolSize,
     final StreamConsumerFactory consumerFactory,
     final BufferPool bufferPool,
     int timeout,
     TimeUnit unit,
     final boolean readSingleDatagram)
     throws IOException {
   this.executor =
       Executors.newScheduledThreadPool(
           threadPoolSize + 1); // need to allow for long running ChannelDispatcher thread
   this.serverSocketSelector = Selector.open();
   this.socketChannelSelector = Selector.open();
   this.bufferPool = bufferPool;
   this.initialBufferPoolSize = bufferPool.size();
   channelDispatcher =
       new ChannelDispatcher(
           serverSocketSelector,
           socketChannelSelector,
           executor,
           consumerFactory,
           bufferPool,
           timeout,
           unit,
           readSingleDatagram);
   executor.schedule(channelDispatcher, 50, TimeUnit.MILLISECONDS);
 }
Example #21
0
  public void clearBuffs(final CreatureObject creature) {

    // copy to array for thread safety

    for (final Buff buff : creature.getBuffList().get().toArray(new Buff[] {})) {

      if (buff.getGroup1().startsWith("setBonus")) {
        continue;
      }

      if (buff.isGroupBuff() && buff.getGroupBufferId() != creature.getObjectID()) {
        removeBuffFromCreature(creature, buff);
        continue;
      }

      if (buff.getRemainingDuration() > 0 && buff.getDuration() > 0) {
        ScheduledFuture<?> task =
            scheduler.schedule(
                new Runnable() {

                  @Override
                  public void run() {

                    removeBuffFromCreature(creature, buff);
                  }
                },
                (long) buff.getRemainingDuration(),
                TimeUnit.SECONDS);
        buff.setRemovalTask(task);
        continue;
      } else {
        removeBuffFromCreature(creature, buff);
      }
    }
  }
 public void oneDay(
     Runnable command, int year, int month, int day, int hour, int minute, int second) {
   long delay =
       Utils.getDate(year, month, day, hour, minute, second).getTime()
           - System.currentTimeMillis();
   service.schedule(command, delay, TimeUnit.MILLISECONDS);
 }
Example #23
0
  public static void timedRun(final Runnable r, long timeout, TimeUnit unit)
      throws InterruptedException {
    class RethrowableTask implements Runnable {
      private volatile Throwable t;

      public void run() {
        try {
          r.run();
        } catch (Throwable t) {
          this.t = t;
        }
      }

      void rethrow() {
        if (t != null) throw launderThrowable(t);
      }
    }

    RethrowableTask task = new RethrowableTask();
    final Thread taskThread = new Thread(task);
    taskThread.start();
    cancelExec.schedule(
        new Runnable() {
          public void run() {
            taskThread.interrupt();
          }
        },
        timeout,
        unit);
    taskThread.join(unit.toMillis(timeout));
    task.rethrow();
  }
Example #24
0
    public void zza(Context context, zzmo zzmo, long l, zzmy zzmy)
    {
        this;
        JVM INSTR monitorenter ;
        zzbg.zzam("ResourceLoaderScheduler: Loading new resource.");
        if (zzaEL == null)
        {
            break MISSING_BLOCK_LABEL_17;
        }
        this;
        JVM INSTR monitorexit ;
        return;
        if (zzaCO == null)
        {
            break MISSING_BLOCK_LABEL_66;
        }
        context = new zzmz(context, zzmo, zzmy, zzaCO);
_L1:
        zzaEL = zzaEJ.schedule(context, l, TimeUnit.MILLISECONDS);
        this;
        JVM INSTR monitorexit ;
        return;
        context;
        this;
        JVM INSTR monitorexit ;
        throw context;
        context = new zzmz(context, zzmo, zzmy);
          goto _L1
Example #25
0
  @TextChange(R.id.inputSearch)
  public void searchForMemberByPagination() {
    emptySearch.setVisibility(View.INVISIBLE);
    loading.setVisibility(View.VISIBLE);
    listViewMembers.setVisibility(View.INVISIBLE);
    firstTimeSearch = true;

    Runnable task =
        new Runnable() {
          public void run() {
            if (!waitForSearch) {
              waitForSearch = true;
              from = 0;
              membersList = new ArrayList<Member>();
              members = new ArrayList<HashMap<String, String>>();

              noMoreMembers = false;
              if (!inputSearch.getText().toString().isEmpty()) {
                searchForMembersByPaginationService(inputSearch.getText().toString());
                listViewMembers.setVisibility(View.INVISIBLE);
                loading.setVisibility(View.VISIBLE);
                emptySearch.setVisibility(View.INVISIBLE);
              } else {
                listAllMembersByPaginationService();
                loading.setVisibility(View.VISIBLE);
                listViewMembers.setVisibility(View.INVISIBLE);
                emptySearch.setVisibility(View.INVISIBLE);
              }
            }
          }
        };

    worker.schedule(task, 2, TimeUnit.SECONDS);
  }
Example #26
0
 @Override
 public void process(TimedAction<TimedEvent> action) {
   scheduledExecutorService.schedule(
       () -> targetActionProcessor.process(action.getTargetAction()),
       Duration.between(LocalDateTime.now(), action.getDateTime()).toMillis(),
       TimeUnit.MILLISECONDS);
 }
  /** Start device found scheduled service */
  void startDeviceFoundVerificationService() {
    Log.d(
        TAG,
        "Start DeviceFoundVerificationService for device: '"
            + deviceId
            + "', the verification will be done after: "
            + DEVICE_FOUND_TIME
            + " seconds");

    // If the process started previously -> stop it
    stopDeviceFoundVerificationService();

    scheduledService = Executors.newScheduledThreadPool(1);
    scheduledService.schedule(
        new Runnable() {
          @Override
          public void run() {
            Log.d(
                TAG,
                "DeviceFoundVerificationService is wake up, set the device: '"
                    + deviceId
                    + "' reachability to 'false'");
            isReachable.set(false);
            deviceRegistry.reachabilityChanged(ControllableDevice.this, false);
          }
        },
        DEVICE_FOUND_TIME,
        TimeUnit.SECONDS);
  } // startDeviceFoundVerification
  /**
   * This test executes method {@link
   * com.github.joelittlejohn.embedmongo.PortUtils#allocateRandomPort()} many times concurrently to
   * make sure that port allocation works correctly under stress.
   */
  @Test
  public void testAllocateRandomPort() throws Exception {
    final int testAllocationCount = 10000;
    final CountDownLatch allocationsCounter = new CountDownLatch(testAllocationCount);

    final Runnable allocatePort =
        new Runnable() {
          @Override
          public void run() {
            int port = -1;
            try {
              port = PortUtils.allocateRandomPort();
              new ServerSocket(port);
              // port has been bound successfully
            } catch (IOException e) {
              throw new RuntimeException("Port " + port + " cannot be bind!");
            } finally {
              allocationsCounter.countDown();
            }
          }
        };

    final Random randomGenerator = new Random();
    for (int i = 0; i < testAllocationCount; i++) {
      // schedule execution a little to in the future to simulate less predictable environment
      testPooledExecutor.schedule(allocatePort, randomGenerator.nextInt(10), TimeUnit.MILLISECONDS);
    }
    allocationsCounter.await(10, TimeUnit.SECONDS);
  }
Example #29
0
  // Called when UI activities all pause, terminates the service
  // unless canceled.
  //
  public void startBackgroundTimeout() {

    // Cancel any pre-existing timeout.
    cancelBackgroundTimeout();

    Runnable task =
        new Runnable() {
          public void run() {
            mLogger.info("background timeout");
            mApp.doExit();
          }
        };

    String delaystr = mPrefs.getString(SettingsActivity.KEY_BACKGROUND_TIMEOUT, "600");
    long delay;
    try {
      delay = Long.parseLong(delaystr);
    } catch (NumberFormatException ex) {
      throw new RuntimeException(ex.toString()); // Shouldn't happen.
    }

    if (delay != -1) {
      mBackgroundTimeout = mTimeoutWorker.schedule(task, delay, TimeUnit.SECONDS);

      mLogger.info(String.format("background timeout scheduled in %d seconds", delay));
    }
  }
Example #30
0
 private void dispatchHandler() {
   scheduleHandler = new ScheduleHandler();
   managementExecutor.schedule(
       scheduleHandler,
       timingQueue.first().nextTime - System.currentTimeMillis(),
       TimeUnit.MILLISECONDS);
 }