如何使用ScheduledExecutorService更改重复任务的速率或周期? [英] How do I change the rate or period of a repeating task using ScheduledExecutorService?

查看:1986
本文介绍了如何使用ScheduledExecutorService更改重复任务的速率或周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个蓝牙聊天示例应用程序的修改版本。我已经设置了 ScheduledExecutorService ,它使用 scheduleAtFixedRate 以预定义的速率通过蓝牙发送命令。

I have a modified version of the bluetooth chat sample app. I have set up a ScheduledExecutorService which sends a command over bluetooth at a predefined rate using scheduleAtFixedRate.

我已设置 PreferenceActivity 以允许用户修改期间。但我不确定如何在更新期间实现重复的实际任务。我是否需要以某种方式取消并重新启动 ScheduledExecutorService

I have set up a PreferenceActivity to allow the period to be modified by the user. But I'm unsure how to get the actual recurring tasks to happen with the updated period. Do I need to cancel and restart the ScheduledExecutorService somehow?

这是我的代码的相关部分。

Here's the relevant parts of my code.

private ScheduledExecutorService scheduleTaskExecutor;

public long ReadInterval = 1;

...    

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
...
    // This schedule a task to run every 1 second:
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {


        // If you need update UI, simply do this:
         runOnUiThread(new Runnable() {
            public void run() {
            // update your UI component here.
              if (connected == true) {
                  sendMessage("READ");                
                  if (D) Log.i(TAG, "In Run!");                   
              }
            }
        });
      }
    }, 0, ReadInterval, TimeUnit.SECONDS);      
    }

我试图更新 ReadInterval 这里。 ReadInterval 正在更新,但定期命令期间不会更新。

And I was trying to update ReadInterval here. The ReadInterval is getting updated but the recurring command period does not get updated.

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (D)
        Log.d(TAG, "onActivityResult " + resultCode);
    switch (requestCode) {
    case REQUEST_CONNECT_DEVICE:
...
    case REQUEST_ENABLE_BT:
...
    case REQUEST_SETTINGS:
        // When returning from settings activity
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        String Pref = sharedPref.getString(SettingsActivity.KEY_PREF_READINTERVAL, "");
        ReadInterval = Long.valueOf(Pref);
        Toast.makeText(this, Pref,
                    Toast.LENGTH_SHORT).show();

        Log.d(TAG, "Settings Activity Result");
    }
}


推荐答案

我改进了答案(主要是因为我也必须使用 ScheduledExecutorService )。请使用此代码而不是我之前发布的代码,因为之前的代码实际上是在性能上,没有充分的理由。

I improved the answer a bit (mainly because I too had to use ScheduledExecutorService). Please use this code instead of the previous one I posted, because the previous one was really on performance, for no good reason.

private ScheduledExecutorService scheduledExecutorService;
private ScheduledFuture<?> futureTask;
private Runnable myTask;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    // Your executor, you should instanciate it once for all
    scheduledExecutorService = Executors.newScheduledThreadPool(5);

    // Since your task won't change during runtime, you can instanciate it too once for all
    myTask = new Runnable()
    {
        @Override
        public void run()
        {
            // Your code to run periodically
        }
    };
}

/**
 * This method will reschedule "myTask" with the new param time
 */
public void changeReadInterval(long time)
{
    if(time > 0)
    {       
        if (futureTask != null)
        {
            futureTask.cancel(true);
        }

        futureTask = scheduledExecutorService.scheduleAtFixedRate(myTask, 0, time, TimeUnit.SECONDS);
    }
}

现在,要在运行时重新安排任务,请使用方法 changeReadInterval(时间);

Now, to reschedule your task during runtime, use the method changeReadInterval(time);

如果已经设置并将重新安排,它将取消之前的计时器一个新的。

It will cancel the previous "timer" if it has been set and will reschedule a new one.

这篇关于如何使用ScheduledExecutorService更改重复任务的速率或周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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