public static void main(String[] args) throws NoSuchProviderException, NoSuchAlgorithmException {
    System.out.println("Starting rfid-reader2keyboard");

    Security.insertProviderAt(new Smartcardio(), 1);
    TerminalFactory.getInstance("PC/SC", null);

    System.out.println("The following terminals were detected:");
    System.out.println(Read.listTerminals());

    System.out.println();
    System.out.println(
        "inventid RFID capturing is currently active. Close this dialog to deactivate.");
    System.out.println(
        "The most likely reason you see this is in order to resolve any issue you ay have found. Please follow"
            + " the instructions of inventid support and send these lines to the given email address");

    executorService.scheduleAtFixedRate(errorLogger, 10, 30, TimeUnit.SECONDS);
    executorService.scheduleAtFixedRate(detectorLoop, 10, 15, TimeUnit.SECONDS);

    Read reader = new Read();
    reader.startRunning();

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                executorService.shutdownNow();
                System.out.println(
                    "inventid RFID capturing is now inactive. You can close this dialog");
              }
            });
  }
Exemple #2
0
  @Override
  public void shutdown() {
    RuntimeException exception = null;
    try {
      if (executor != null) {
        executor.shutdownNow();
        executor.awaitTermination(5, TimeUnit.SECONDS);
        executor = null;
      }
    } catch (RuntimeException e) {
      exception = e;
    } catch (InterruptedException e) {
      exception = new RuntimeException(e);
    }

    try {
      if (scheduledExecutor != null) {
        scheduledExecutor.shutdown();
        scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS);
        scheduledExecutor = null;
      }
    } catch (RuntimeException e) {
      exception = e;
    } catch (InterruptedException e) {
      exception = new RuntimeException(e);
    }

    if (exception != null) {
      throw new RuntimeException("Unable to shut down job scheduler properly.", exception);
    }
  }
Exemple #3
0
  @Override
  public void onApplicationStop() {

    List<Class> jobs = Play.classloader.getAssignableClasses(Job.class);

    for (final Class clazz : jobs) {
      // @OnApplicationStop
      if (clazz.isAnnotationPresent(OnApplicationStop.class)) {
        try {
          Job<?> job = ((Job<?>) clazz.newInstance());
          scheduledJobs.add(job);
          job.run();
          if (job.wasError) {
            if (job.lastException != null) {
              throw job.lastException;
            }
            throw new RuntimeException("@OnApplicationStop Job has failed");
          }
        } catch (InstantiationException e) {
          throw new UnexpectedException("Job could not be instantiated", e);
        } catch (IllegalAccessException e) {
          throw new UnexpectedException("Job could not be instantiated", e);
        } catch (Throwable ex) {
          if (ex instanceof PlayException) {
            throw (PlayException) ex;
          }
          throw new UnexpectedException(ex);
        }
      }
    }

    executor.shutdownNow();
    executor.getQueue().clear();
  }
Exemple #4
0
  /**
   * Creates a thread pool that can schedule commands to run after a given delay, or to execute
   * periodically.
   *
   * @param corePoolSize Number of threads to keep in the pool, even if they are idle.
   * @param threadName Part of thread name that would be used by thread factory.
   * @return Newly created scheduled thread pool.
   */
  private static ScheduledExecutorService newScheduledThreadPool(
      int corePoolSize, final String threadName) {
    ScheduledExecutorService srvc =
        Executors.newScheduledThreadPool(
            corePoolSize,
            new ThreadFactory() {
              @Override
              public Thread newThread(Runnable r) {
                Thread thread =
                    new Thread(r, String.format("%s-%d", threadName, THREAD_CNT.getAndIncrement()));

                thread.setDaemon(true);

                return thread;
              }
            });

    ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) srvc;

    // Setting up shutdown policy.
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);

    return srvc;
  }
  /**
   * Implements the Token Bucket algorithm to provide a maximum number of invocations within each
   * fixed time window. Useful for rate-limiting. If given a non-null executor, the scheduled
   * runnables are passed to that executor for execution at the rate limit. If executor is null, a
   * single-threaded executor is used
   *
   * @param executor the Executor which executes the Runnables. the executor is not called with the
   *     runnable until the rate limit has been fulfilled
   * @param invocations number of queries allowed during each time window
   * @param per the duration of each time window
   */
  public RateLimiter(Executor executor, final int invocations, final Duration per) {
    if (executor != null) {
      this.executor = executor;
    } else {
      this.executor = Executors.newSingleThreadExecutor();
    }

    // This thread fills the TokenBucket with available requests every time window
    ScheduledThreadPoolExecutor replenisher = new ScheduledThreadPoolExecutor(1);
    replenisher.scheduleAtFixedRate(
        new Runnable() {
          public void run() {
            int permitsToCreate = invocations - requestsAvailable.availablePermits();
            if (permitsToCreate > 0) {
              synchronized (requestsAvailable) {
                // bring the number of requests up to the maximum size per time window
                requestsAvailable.release(permitsToCreate);
              }
            }
          }
        },
        0,
        per.getMillis(),
        TimeUnit.MILLISECONDS);

    pump = new RunnablePump();
    pump.start();
  }
 public void purge() {
   _effectsScheduledThreadPool.purge();
   _generalScheduledThreadPool.purge();
   _aiScheduledThreadPool.purge();
   _ioPacketsThreadPool.purge();
   _generalPacketsThreadPool.purge();
   _generalThreadPool.purge();
 }
  @Override
  public synchronized void stop() {
    for (Runnable runnable : executor.getQueue()) {
      ((RunnableFuture<?>) runnable).cancel(false);
    }

    executor.purge();
  }
 @Override
 public SubmitterScheduler makeSubmitterScheduler(int poolSize, boolean prestartIfAvailable) {
   ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize);
   if (prestartIfAvailable) {
     executor.prestartAllCoreThreads();
   }
   executors.add(executor);
   return new ScheduledExecutorServiceWrapper(executor);
 }
  /**
   * Creates a {@link ScheduledThreadPoolExecutor} with custom name for the threads.
   *
   * @param name the prefix to add to the thread name in ThreadFactory.
   * @return The default thread pool for request timeout and client execution timeout features.
   */
  public static ScheduledThreadPoolExecutor buildDefaultTimeoutThreadPool(final String name) {
    ScheduledThreadPoolExecutor executor =
        new ScheduledThreadPoolExecutor(5, getThreadFactory(name));
    safeSetRemoveOnCancel(executor);
    executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    executor.allowCoreThreadTimeOut(true);

    return executor;
  }
 public static void main(String[] args) {
   // Schedule a task using only Java ThreadExecutor
   System.out.println("Main Thread started");
   MyTask myTask = new MyTask();
   int corePoolSize = 5;
   ScheduledThreadPoolExecutor myExecutor = new ScheduledThreadPoolExecutor(corePoolSize);
   // myExecutor.scheduleAtFixedRate(myTask, 1000, 2000, TimeUnit.MILLISECONDS);
   myExecutor.scheduleAtFixedRate(myTask, 0, 1, TimeUnit.DAYS);
   System.out.println("Main Thread ended");
 }
Exemple #11
0
  @Modified
  public void modified(Map<String, ?> properties) {
    final Configuration conf = Configuration.create(properties);
    m_conf = conf;

    final int numberOfThreads = conf.numberOfThreads();
    if (m_executor.getCorePoolSize() != numberOfThreads) {
      m_executor.setCorePoolSize(numberOfThreads);
      c_logger.info("Scheduler modified: numberOfThreads={}", numberOfThreads);
    }
  }
Exemple #12
0
 private String debug() {
   _executor.purge(); // Remove cancelled tasks from the queue so we get a good queue size stat
   return " Pool: "
       + _name
       + " Active: "
       + _executor.getActiveCount()
       + '/'
       + _executor.getPoolSize()
       + " Completed: "
       + _executor.getCompletedTaskCount()
       + " Queued: "
       + _executor.getQueue().size();
 }
  /* CONSTRUCTOR */
  public ServiceSensorControl() {
    // Register this object globally
    GlobalContext.set(this);

    // Create the executor service, keep two threads in the pool
    executorService =
        new ScheduledThreadPoolExecutor(SensorCollectionOptions.MAIN_EXECUTOR_CORE_POOL);

    // If feature is available, enable core thread timeout with five seconds
    if (Build.VERSION.SDK_INT >= 9) {
      executorService.setKeepAliveTime(MAIN_EXECUTOR_CORE_TIMEOUT, TimeUnit.MILLISECONDS);
      executorService.allowCoreThreadTimeOut(true);
    }
  }
Exemple #14
0
  public void deactivate() {
    final ScheduledThreadPoolExecutor executor = m_executor;
    executor.shutdown();
    try {
      executor.awaitTermination(m_conf.terminationWaitTimeInSeconds(), TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }

    m_executor = null;
    m_conf = null;

    c_logger.info("Scheduler deactivated");
  }
 @Override
 protected void serviceStop() throws Exception {
   if (sched != null) {
     sched.shutdown();
     boolean terminated = false;
     try {
       terminated = sched.awaitTermination(10, SECONDS);
     } catch (InterruptedException e) {
     }
     if (terminated != true) {
       sched.shutdownNow();
     }
   }
   super.serviceStop();
 }
  /**
   * Submit the work for actual execution.
   *
   * @throws InvalidProtocolBufferException
   */
  public void submitWork(SubmitWorkRequestProto request, String llapHost, int llapPort) {
    // Register the pending events to be sent for this spec.
    VertexOrBinary vob = request.getWorkSpec();
    assert vob.hasVertexBinary() != vob.hasVertex();
    SignableVertexSpec vertex = null;
    try {
      vertex =
          vob.hasVertex() ? vob.getVertex() : SignableVertexSpec.parseFrom(vob.getVertexBinary());
    } catch (InvalidProtocolBufferException e) {
      throw new RuntimeException(e);
    }
    QueryIdentifierProto queryIdentifierProto = vertex.getQueryIdentifier();
    TezTaskAttemptID attemptId =
        Converters.createTaskAttemptId(
            queryIdentifierProto,
            vertex.getVertexIndex(),
            request.getFragmentNumber(),
            request.getAttemptNumber());
    final String fragmentId = attemptId.toString();

    pendingEvents.putIfAbsent(
        fragmentId,
        new PendingEventData(
            new TaskHeartbeatInfo(fragmentId, llapHost, llapPort), Lists.<TezEvent>newArrayList()));

    // Setup timer task to check for hearbeat timeouts
    timer.scheduleAtFixedRate(
        new HeartbeatCheckTask(), connectionTimeout, connectionTimeout, TimeUnit.MILLISECONDS);

    // Send out the actual SubmitWorkRequest
    communicator.sendSubmitWork(
        request,
        llapHost,
        llapPort,
        new LlapProtocolClientProxy.ExecuteRequestCallback<SubmitWorkResponseProto>() {

          @Override
          public void setResponse(SubmitWorkResponseProto response) {
            if (response.hasSubmissionState()) {
              if (response.getSubmissionState().equals(SubmissionStateProto.REJECTED)) {
                String msg = "Fragment: " + fragmentId + " rejected. Server Busy.";
                LOG.info(msg);
                if (responder != null) {
                  Throwable err = new RuntimeException(msg);
                  responder.submissionFailed(fragmentId, err);
                }
                return;
              }
            }
          }

          @Override
          public void indicateError(Throwable t) {
            String msg = "Failed to submit: " + fragmentId;
            LOG.error(msg, t);
            Throwable err = new RuntimeException(msg, t);
            responder.submissionFailed(fragmentId, err);
          }
        });
  }
  private void recover(RecoveredDeletionServiceState state) throws IOException {
    List<DeletionServiceDeleteTaskProto> taskProtos = state.getTasks();
    Map<Integer, DeletionTaskRecoveryInfo> idToInfoMap =
        new HashMap<Integer, DeletionTaskRecoveryInfo>(taskProtos.size());
    Set<Integer> successorTasks = new HashSet<Integer>();
    for (DeletionServiceDeleteTaskProto proto : taskProtos) {
      DeletionTaskRecoveryInfo info = parseTaskProto(proto);
      idToInfoMap.put(info.task.taskId, info);
      nextTaskId.set(Math.max(nextTaskId.get(), info.task.taskId));
      successorTasks.addAll(info.successorTaskIds);
    }

    // restore the task dependencies and schedule the deletion tasks that
    // have no predecessors
    final long now = System.currentTimeMillis();
    for (DeletionTaskRecoveryInfo info : idToInfoMap.values()) {
      for (Integer successorId : info.successorTaskIds) {
        DeletionTaskRecoveryInfo successor = idToInfoMap.get(successorId);
        if (successor != null) {
          info.task.addFileDeletionTaskDependency(successor.task);
        } else {
          LOG.error(
              "Unable to locate dependency task for deletion task "
                  + info.task.taskId
                  + " at "
                  + info.task.getSubDir());
        }
      }
      if (!successorTasks.contains(info.task.taskId)) {
        long msecTilDeletion = info.deletionTimestamp - now;
        sched.schedule(info.task, msecTilDeletion, TimeUnit.MILLISECONDS);
      }
    }
  }
Exemple #18
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_child_on_bus);
    viewHolder = new ViewHolder();

    // Set on bus status
    ParseCloudManager.getInstance().setStatusForSelfAndNotifyParents(TravelingData.ON_BUS);

    // Initiate views
    initiateViews();

    // Get data from intent
    travelingData = getIntent().getParcelableExtra("data");

    // Set trip information from travelingData
    viewHolder.busStopName.setText(travelingData.busStopName);
    viewHolder.timeToStop.setText(travelingData.busArrivingAt);

    // Check if next bus stop is yours, and if the bus have left the last one each 20s
    poolExecutor = new ScheduledThreadPoolExecutor(1);
    poolExecutor.scheduleWithFixedDelay(this, 0, 20, TimeUnit.SECONDS);

    // Dummy buttons, pass forward
    addButtonListener();
    // Init service
    Intent serviceIntent = new Intent(context, UpdateLocToParseService.class);
    bindService(serviceIntent, this, 0);
  }
  /**
   * Sends a Spine message. This is a wrapper round the Transmitter thread and registers the message
   * with the retry mechanism if the contract properties require. It will also, for asynchronous
   * messages, start the listener if it is not already running.
   *
   * @param s Concrete instance of Sendable, encapsulating the message to send.
   * @param c SDS details of recipient
   * @throws Exception if there was a Connection Manager boot exception, or if starting any required
   *     listener fails,
   */
  public void send(Sendable s, SdsTransmissionDetails c) throws Exception {
    // Note: check this here so getInstance() doesn't have to throw any
    // exception - that means that we don't have to catch them in the
    // Transmitter, which can just log if anything goes wrong with its
    // own processing.
    //
    if (bootException != null) throw bootException;

    if (!c.isSynchronous()) {
      listen();
      if ((s.getType() != Sendable.ACK) && (c.getDuplicateElimination().contentEquals("always"))) {
        synchronized (LOGSOURCE) {
          if (timer == null) {
            timer = new ScheduledThreadPoolExecutor(TIMER_THREAD_POOL_SIZE);
            RetryProcessor rp = new RetryProcessor();
            timer.scheduleAtFixedRate(
                rp, retryCheckPeriod, retryCheckPeriod, TimeUnit.MILLISECONDS);
          }
        }
        if (!requests.containsKey(s.getMessageId())) {
          requests.put(s.getMessageId(), s);
        }
      }
    }
    Transmitter t = new Transmitter(s);
    t.start();
  }
  private void makeLod(
      final LodGenerator.TriangleReductionMethod method, final float value, final int ll) {
    exec.execute(
        new Runnable() {
          public void run() {
            for (final Geometry geometry : listGeoms) {
              LOG.info("make lod for " + geometry + ", value=" + value);
              LodGenerator lODGenerator = new LodGenerator(geometry);
              final VertexBuffer[] lods = lODGenerator.computeLods(method, value);
              LOG.info("LOD levels: " + lods.length);

              enqueue(
                  new Callable<Void>() {
                    public Void call() throws Exception {
                      geometry.getMesh().setLodLevels(lods);
                      lodLevel = 0;
                      if (geometry.getMesh().getNumLodLevels() > ll) {
                        lodLevel = ll;
                      }
                      geometry.setLodLevel(lodLevel);
                      hudText.setText(computeNbTri() + " tris");
                      return null;
                    }
                  });
            }
          }
        });
  }
  @Override
  public void start() {
    super.start();
    setRunning(true);

    Log.d(TAG, "Starting Location sensor");

    // Use any provider (LOCATION, Network or Passive)
    addLocationListenerWithAllProviders();

    IntentFilter intentFilter = new IntentFilter(LOCATION_UPDATE_ACTION);
    getContext().registerReceiver(locationReceiver, intentFilter);

    Log.d(TAG, "Starting Location sensor [done]");

    Sensor.setSensorStatus(Sensor.SENSOR_LOCATION, Sensor.SENSOR_ON);
    refreshStatus();

    if (stpe == null) {
      stpe = new ScheduledThreadPoolExecutor(1);
      stpe.scheduleAtFixedRate(controller, 0, Utilities.LOCATION_CHECK_TIME, TimeUnit.MILLISECONDS);
      /*stpe.scheduleAtFixedRate(controller, MAX_TIME_WITHOUT_NEW_LOCATION,
      MAX_TIME_WITHOUT_NEW_LOCATION, TimeUnit.MILLISECONDS);*/
    }
  }
 public SenderPool() {
   this.saorl = new LinkedList<SenderAddedOrRemovedListener>();
   this.statsListeners = new LinkedList<OverallSenderStatisticsUpdatedListener>();
   analyzer = new OverallSenderStatisticAnalyzer();
   this.stfe = new ScheduledThreadPoolExecutor(threadPoolSize);
   stfe.scheduleAtFixedRate(analyzer, statsInterval, statsInterval, TimeUnit.MILLISECONDS);
 }
Exemple #23
0
 public static ScheduledExecutorService getExecutor(
     ThreadGroup group, String namePrefix, int threadCount, boolean preStart) {
   if (threadCount == 0) {
     threadCount = 1;
   } else if (threadCount < 0) {
     int numCpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
     threadCount = Math.abs(threadCount) * numCpus;
   }
   ThreadFactory threadFactory = createThreadFactory(group, namePrefix);
   ScheduledThreadPoolExecutor executor =
       new ScheduledThreadPoolExecutor(threadCount, threadFactory);
   if (preStart) {
     executor.prestartAllCoreThreads();
   }
   return executor;
 }
Exemple #24
0
  /** 从数据库获取待发送数据 */
  private void startWatchData() {
    watchDataThreadPool.scheduleAtFixedRate(
        new Runnable() {
          @Override
          public void run() {
            // 数据库查询出来并锁定的数据
            List<SmQueue> temp = new ArrayList<SmQueue>();

            int limit = smgFlowLimit - queue.size();
            if (limit > 0) {
              DatabaseTransaction trans = new DatabaseTransaction(true);
              try {
                temp = new DbService(trans).getMsgFromQueueAndLockMsg(channel.getId(), limit);
                trans.commit();
              } catch (Exception ex) {
                ChannelLog.log(
                    Logger.getLogger(SubmitThread.class),
                    ex.getMessage(),
                    LevelUtils.getErrLevel(channel.getId()));
                trans.rollback();
              } finally {
                trans.close();
              }

              if (temp.size() > 0) {
                queue.addAll(temp);
              }
            }
          }
        },
        1000,
        1000,
        TimeUnit.MILLISECONDS);
  }
Exemple #25
0
 /** 改变标志位停止线程 */
 public void stop_() {
   synchronized (this) {
     isContinue = false;
     watchDataThreadPool.shutdown();
     submitDataThreadPool.shutdown();
   }
 }
 /** Schedules the notification updater task if it hasn't been scheduled yet. */
 private void setupNotificationUpdater() {
   if (AppConfig.DEBUG) Log.d(TAG, "Setting up notification updater");
   if (notificationUpdater == null) {
     notificationUpdater = new NotificationUpdater();
     notificationUpdaterFuture =
         schedExecutor.scheduleAtFixedRate(notificationUpdater, 5L, 5L, TimeUnit.SECONDS);
   }
 }
Exemple #27
0
  /** @param runFrequency implemented only for TimeUnit granularity - Seconds */
  public static void schedule(Runnable runnable, Duration runFrequency, TimerType timerType) {
    switch (timerType) {
      case OneTimeRun:
        long seconds = runFrequency.getSeconds();
        if (seconds > 0) executor.schedule(runnable, seconds, TimeUnit.SECONDS);
        else executor.schedule(runnable, runFrequency.toMillis(), TimeUnit.MILLISECONDS);
        break;

      case RepeatRun:
        executor.scheduleWithFixedDelay(
            runnable, runFrequency.getSeconds(), runFrequency.getSeconds(), TimeUnit.SECONDS);
        break;

      default:
        throw new UnsupportedOperationException("Unsupported timer pattern.");
    }
  }
Exemple #28
0
 @Override
 protected void afterExecute(Runnable r, Throwable t) {
   super.afterExecute(r, t);
   if (t != null) { // shoudn't happen, caught in RunnableEvent.run()
     Log log = I2PAppContext.getGlobalContext().logManager().getLog(SimpleTimer2.class);
     log.log(Log.CRIT, "wtf, event borked: " + r, t);
   }
 }
Exemple #29
0
  public void internalSchedule(TimerJobInstance timerJobInstance) {
    Date date = timerJobInstance.getTrigger().hasNextFireTime();
    Callable<Void> item = (Callable<Void>) timerJobInstance;

    JDKJobHandle jobHandle = (JDKJobHandle) timerJobInstance.getJobHandle();
    long then = date.getTime();
    long now = System.currentTimeMillis();
    ScheduledFuture<Void> future = null;
    if (then >= now) {
      future = scheduler.schedule(item, then - now, TimeUnit.MILLISECONDS);
    } else {
      future = scheduler.schedule(item, 0, TimeUnit.MILLISECONDS);
    }

    jobHandle.setFuture(future);
    jobFactoryManager.addTimerJobInstance(timerJobInstance);
  }
 @Override
 public void serviceStop() {
   llapTaskUmbilicalServer.shutdownServer();
   timer.shutdown();
   if (this.communicator != null) {
     this.communicator.stop();
   }
 }