如何使用scheduleAtFixedRate用于执行在每个第二如何使用、在每个、scheduleAtFixedRate

2023-09-04 05:37:50 作者:梦想如花般盛开

在以下code的send()函数执行多次在第二,我想在第二个执行的send()一次,我该如何改变code

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.scheduleAtFixedRate(
            new TimerTask() {
                public void run() {
                    try {
                        send();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            },
            1000,
            1000);

发送功能,下面给出

send function is given below

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");
    }
}

输出的logcat下面给出

Logcat output is given below

推荐答案

我换成带有计时器的Runnable /处理程序最近,它更容易

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);
 
精彩推荐