连续暂停/停止和启动/恢复 Java TimerTask? [英] Pausing/stopping and starting/resuming Java TimerTask continuously?

查看:49
本文介绍了连续暂停/停止和启动/恢复 Java TimerTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Java TimerTask 的简单问题.如何根据特定条件暂停/恢复两个 TimerTask 任务?例如,我有两个相互之间运行的计时器.当第一个定时器的任务内部满足某个条件时,第一个定时器停止并启动第二个定时器,当第二个定时器的任务内部满足某个条件时也会发生同样的事情.下面的课程正是我的意思:

I have one simple question regarding Java TimerTask. How do I pause/resume two TimerTask tasks based on a certain condition? For example I have two timers that run between each other. When a certain condition has been met inside the task of first timer, the first timer stops and starts the second timer, and the same thing happens when a certain condition has been met inside the task of second timer. The class below shows exactly what I mean:

public class TimerTest {
    Timer timer1;
    Timer timer2;
    volatile boolean a = false;

    public TimerTest() {
        timer1 = new Timer();
        timer2 = new Timer();     
    }

    public void runStart() {
        timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
    }

    class Task1 extends TimerTask {
        public void run() {
            System.out.println("Checking a");
            a = SomeClass.getSomeStaticValue();

            if (a) {
                // Pause/stop timer1, start/resume timer2 for 5 seconds
                timer2.schedule(new Task2(), 5000);
            }
        }
    }

    class Task2 extends TimerTask{
        public void run() {
            System.out.println("Checking a");
            a = SomeClass.getSomeStaticValue();

            if (!a) {
                // Pause/stop timer2, back to timer1
                timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
            }

            // Do something...
        }
    }

    public static void main(String args[]) {
        TimerTest tt = new TimerTest();
        tt.runStart();      
    }
}

所以我的问题是,如何在运行 timer2 时暂停 timer1 以及在 timer2 运行时暂停?性能和时间是我的主要关注点,因为这需要在另一个正在运行的线程中实现.顺便说一下,我正在尝试在 Android 上实现这些并发计时器.

So my question is, how do I pause timer1 while running timer2 and vice versa while timer2 is running? Performance and timing is my main concern as this needs to be implemented inside another running thread. By the way I am trying to implement these concurrent timers on Android.

感谢您的帮助!

推荐答案

来自 TimerTask.cancel():

注意从在重复的 run 方法中定时器任务绝对保证定时器任务将不会再次运行.

Note that calling this method from within the run method of a repeating timer task absolutely guarantees that the timer task will not run again.

所以一旦取消,它就不会再运行了.你最好使用更现代的 ScheduledExecutorService(来自 Java 5+).

So once cancelled, it won't ever run again. You'd be better off instead using the more modern ScheduledExecutorService (from Java 5+).

基本结构是:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);

但是查看它后,如果不关闭服务就无法取消该任务,这有​​点奇怪.

but looking into it there's no way of cancelling that task once its started without shutting down the service, which is a bit odd.

TimerTask 在这种情况下可能更容易,但您需要在启动时创建一个新实例.不能重复使用.

TimerTask might be easier in this case but you'll need to create a new instance when you start one up. It can't be reused.

或者,您可以将每个任务封装为一个单独的瞬态服务:

Alternatively you could encapsulate each task as a separate transient service:

final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
  public void run() {
    a++;
    if (a == 3) {
      exec.shutdown();
      exec = Executors.newSingleThreadScheduledExecutor();
      exec.scheduleAtFixedRate(task2, 0, 1000, TimeUnit.MILLISECONDS)
    }
  }
};
exec.scheduleAtFixedRate(task1, 0, 1000, TimeUnit.MILLISECONDS);

这篇关于连续暂停/停止和启动/恢复 Java TimerTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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