如何使用scheduleAtFixedRate在每秒执行

saj*_*ith 0 android

在下面的代码中send()函数在一秒钟内执行多次,我想在一秒钟内执行一次send(),我如何更改代码

timer.scheduleAtFixedRate(
            new TimerTask() {
                public void run() {
                    try {
                        send();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            },
            1000,
            1000);
Run Code Online (Sandbox Code Playgroud)

发送功能如下

void send() throws Exception, IOException
{
    s=new Socket("10.0.2.2",4200);
    r=new PrintWriter(s.getOutputStream());
    while(true)
    {
        Log.e("msg","hi send\n");
        r.print("hai");
    }
}
Run Code Online (Sandbox Code Playgroud)

Logcat输出如下

在此输入图像描述

Dam*_*ian 7

我最近用Runnables/Handlers替换了计时器,它更容易

//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);
Run Code Online (Sandbox Code Playgroud)