如何使用scheduleAtFixedRate用于执行在每个第二 [英] How to use scheduleAtFixedRate for executing in each second

查看:417
本文介绍了如何使用scheduleAtFixedRate用于执行在每个第二的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下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);

这篇关于如何使用scheduleAtFixedRate用于执行在每个第二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆