2017-05-31 52 views
0

这个想法是我的runnable每分钟运行一次。每20秒运行一次,而不是指定的延迟运行

相反,它运行大约20秒钟,我不知道为什么。

下面是代码:

final Handler handler = new Handler(); 
    Runnable runnable = new Runnable() { 

     @Override 
     public void run() { 
      try{ 
       //Post from Queue & update post 
       if (NetworkUtils.isConnected()) { 

        //post from queue 
        try { 
         postHelper.postFromQueue(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

        //Update posts 
        postHelper.updateSolicitations(); 
       } 
      } 
      catch (Exception e) { 
       // TODO: handle exception 
      } 
      finally{ 
       //also call the same runnable to call it at regular interval 
       handler.postDelayed(this, 60000); 
      } 
     } 
    }; 

我不知道,如果是相关的,但它MainActivity的onCreate方法。

+1

你的代码是确定的。 https://stackoverflow.com/questions/6242268/repeat-a-task-with-a-time-delay – dit

+0

从onPause/onStop删除处理程序的回调文件 – Selvin

+0

@dit这是一个更好的方式来做到这一点,它工作顺利, 谢谢! – Rosenberg

回答

0

也许你可以考虑使用ScheduledExecutorService的

public static void main(String[] args) { 
    ScheduledExecutorService execService 
        = Executors.newScheduledThreadPool(5); 
    execService.scheduleAtFixedRate(()->{ 
     //The repetitive task, say to update Database 
     System.out.println("hi there at: "+ new java.util.Date()); 
    }, Delay, Rate, TimeUnit.MILLISECONDS);//TimeUnit.MILLISECONDS is time unit 
} 
+0

我用我需要的时间来替换TimeUnit.MILISECONDS?它是异步吗?我们正在使用Handler的 – Rosenberg

+0

。 – dit

+0

@Rosenberg您在此任务运行之前替换延迟时间为延迟时间,Rate为重复时间: execService.scheduleAtFixedRate(() - > { //重复性任务,假设更新数据库 },0 ,6000,TimeUnit.MILLISECONDS); 这将每6秒重复 – dali

-4
Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
    @Override 
    public void run() {          

try{ 
       //Post from Queue & update post 
       if (NetworkUtils.isConnected()) { 

        //post from queue 
        try { 
         postHelper.postFromQueue(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

        //Update posts 
        postHelper.updateSolicitations(); 
       } 
      } 
      catch (Exception e) { 
       // TODO: handle exception 
      } 



    } 
}, 60000); 
0

使用计划中,可以定义一个石英的cronjob只要你定义它是那么触发。

你可以在3点钟

Simple Quartz/Cron job setup

+1

这不是在android – Jon

+0

选项真的是想我不小心跳过了我们正在谈论Android的事实 – Treibholz

-2

做这样的事情每分钟或第二或每天给你介绍可以使用的延迟。 Thread.sleep(60000); 它会使正在运行的线程等待60秒。

+1

在UI线程上使用'Thread.sleep()'是terrbile想法 – Selvin

+0

我新所以它可以帮助我,如果你能解释如何? –

+1

Google for“Android ANR” – Selvin