繁体   English   中英

ScheduledExecutorService和计划的行为

[英]ScheduledExecutorService and scheduled behavior

是否可以使ScheduledExecutorService具有一个正在运行的任务而只有一个正在等待的任务?

  Runnable runnable;
  ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  private volatile ScheduledFuture<?> self;

 protected void waitAndSweep(final String symbol) {
    try { 

        runnable = new Runnable() {
          @Override
          public void run() {
            try {
              long sweepTime = symbolInfo.getSweepTime(symbol);
              long timeSinceLastSweep = System.currentTimeMillis() - sweepTime;
              long waitTime = timeSinceLastSweep >= getInterval() ? 0 : getInterval() - timeSinceLastSweep;
              logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
              if (waitTime > 0){
                Thread.sleep(waitTime);
              }
              callSweep(symbol);
            } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }            
          }
        };

      self = scheduler.schedule(runnable,0,TimeUnit.SECONDS);


    }catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
          "Exception caught...", e);
    }
  }

在上面的代码中,假定调度程序调度了一个可运行的任务,并且正在等待10s(thread.sleep(time)),在此睡眠时间中,如果调度程序调度了其他任务,它将等待。 现在第三个任务进入了调度程序,然后调度程序不应接受它,因为已经有一个正在运行的任务和一个正在等待的任务

您需要使用ScheduledExecutorService还是ThreadPoolExecutor要做? 如果是这样,您可以通过自己创建一个队列(而不是使用Executors.newFixedThreadPool(1))并提供具有定义容量的自己的队列,来控制一次可以排队多少个任务:

  int  oneThread       = 1;
  long zeroKeepAlive   = 0L;
  int  queueDepthOfOne = 1;

  ThreadPoolExecutor threadPoolExecutor =
        new ThreadPoolExecutor(
              oneThread,
              oneThread,
              zeroKeepAlive,
              TimeUnit.MILLISECONDS,
              new ArrayBlockingQueue<Runnable>(queueDepthOfOne)
        );

另外,您可以通过使用spring框架中的ThreadPoolTask​​Executor类,以更少的配置来完成此任务:

ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setQueueCapacity(1);

ThreadPoolTask​​Executor API文档: http : //docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ThreadPoolTask​​Executor.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM