【问题标题】:Run command every 30 minutes in thread on Android service在 Android 服务的线程中每 30 分钟运行一次命令
【发布时间】:2013-06-01 18:45:47
【问题描述】:

我的应用程序在后台运行了一个 Android 服务,该服务运行多个线程,其中一个线程旨在每 30 分钟运行一次命令。

Thread InternetThread = new Thread() {
        public void run() {
            while (true){
                    try {
                        Thread.sleep(1800000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.i("test", "We are running");
                    runCommand();
            }
        }
    };

但是我发现这段代码并不总是每 30 分钟运行一次,有时运行之间可能长达一个小时,从不会少于 30 分钟,但可以更多。我认为这与Android所追求的服务有关吗? 但我不太确定,因为这仅限于我对 Android 服务和线程的理解。

希望有人可以帮助确保“runCommand()”确实每 30 分钟运行一次。

【问题讨论】:

  • 3600000/1000/60 = 60 分钟?
  • 是的,我的错误应该是 1800000 写出了我正在使用的代码 1800000 并得到随机结果
  • @Lestat 1800000 是正确的。
  • 使用 ExcutorService 的 scheduleAtFixedRate
  • @ZacPowell 如果您实现 Thread 或 HandlerThread,请确保您的 UI 线程在等待工作线程完成时不会阻塞——不要调用 Thread.wait() 或 Thread.sleep()。在线程内使用 thread.sleep() 是不好的设计。 developer.android.com/training/articles/perf-anr.html。按照 blackbelt 的建议使用 ExecutorService。警报管理器也可以很好用

标签: java android android-service


【解决方案1】:

进程可能会冻结,试试这个:

Thread InternetThread = new Thread() {
    public void run() {
        long endtime = 0;
        while (true) {
            endTime = System.currentTimeMillis() + 1800000;
            while(System.currentTimeMillis() < endTime) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.i("test", "We are running");
            runCommand();
            }
        }
    };

【讨论】:

  • 如果您实现 Thread 或 HandlerThread,请确保您的 UI 线程在等待工作线程完成时不会阻塞——不要调用 Thread.wait() 或 Thread.sleep()。在线程内使用 thread.sleep() 是不好的设计。 developer.android.com/training/articles/perf-anr.html
猜你喜欢
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多