How to use scheduleAtFixedRate for executing in each second

前端 未结 3 837
谎友^
谎友^ 2020-12-22 09:39

in the below code send() function is executing many times in a second,i want to execute send() once in a second,how i change the code

timer.scheduleAtFixedRa         


        
相关标签:
3条回答
  • 2020-12-22 10:11

    It happened for me when I used a TaskTimer and the phone got into sleep mode. I think it is related to TimerTask using Thread.sleep() to provide the timing. This relies on uptimeMillis() which according to documentation - 'is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls)' Solution would be either to use AlarmManager or WakeLocks.

    0 讨论(0)
  • 2020-12-22 10:11

    an easier approach would look like this:

    new Thread() {
      public void run() {
         while(true) {
           send();
           try{
             Thread.sleep(1000); // pauses for 1 second
           catch(Exception e) {}
         }
      }
    }.start();
    
    0 讨论(0)
  • 2020-12-22 10:15

    I replaced timers with Runnables/Handlers recently, it's much easier

    //declare at top of your activity
    private Handler h = new Handler();
    
    private Runnable myRunnable = new Runnable() {
       public void run() {
        //do stuff  
    
            //run again in one second
        h.postDelayed(myRunnable, 1000);
       }
    };
    
    //trigger the runnable somewhere in your code e.g. onClickHander or onCreate etc
    h.postDelayed(myRunnable, 1000);
    
    0 讨论(0)
提交回复
热议问题