Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从前台服务运行重复任务_Java_Android_Service_Threadpool - Fatal编程技术网

Java 从前台服务运行重复任务

Java 从前台服务运行重复任务,java,android,service,threadpool,Java,Android,Service,Threadpool,我只想从前台服务重复运行任务3次。 我尝试使用ScheduledExecutorService ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1); counter = 0; scheduler.scheduleWithFixedDelay(new Runnable() { public void run() { if (co

我只想从前台服务重复运行任务3次。 我尝试使用
ScheduledExecutorService

 ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);
    counter = 0;
    scheduler.scheduleWithFixedDelay(new Runnable() {
        public void run() {
         if (counter<3) {
            counter++;
            System.out.println("Do something useful");
         }
          else {
            scheduler.shutdownNow()
         }
       }
      }
    }, 2, 2, TimeUnit.SECONDS);
ScheduledExecutorService调度器=执行者
.newScheduledThreadPool(1);
计数器=0;
scheduleWithFixedDelay(新的Runnable(){
公开募捐{

如果(counterHi@mynavy,你的任务重复了3次,你关闭了调度程序
调度程序。shutdownNow()
。那么你不想停止重复的任务吗?Hi@RustFisher,是的,我想在3次之后停止重复的任务,这就是为什么我不确定是否以这种方式使用它取决于你的需要:)我认为现在这是一个很好的方法。谢谢你的评论,对于在后台服务中运行短时间的重复任务,你更喜欢什么替代方法?我认为定时器和调度器都很好。