【问题标题】:Reseting a timer if particular condition is met?如果满足特定条件,则重置计时器?
【发布时间】:2015-08-25 15:32:50
【问题描述】:

我有一个事件监听器,它检测鼠标何时在我的程序的某个窗格中移动。由此,如果鼠标闲置时间过长,我希望能够执行一些操作。

我今天早些时候查看了所有内容,试图找到一个解释和示例,详细说明如何启动、停止/取消和重置计时器,但被不同的方法轰炸尝试并执行这让我很困惑。

我正在关注here 中的计时器示例并针对我自己的情况实施

下面这段代码运行时,每次鼠标停止都会输出“A”。这是不正确的,好像我停止鼠标,快速移动然后再次停止,产生2组“A”。
无论产生多少次停止,这都会继续进行。 我相信我缺少一个“重置计时器”功能,该功能将在鼠标变为移动状态时调用。

我怎样才能实现这个?/这甚至是问题吗?

public class SomeClass{
//...some fancy code...
    if (! isNowMoving) {
        System.out.println("Mouse stopped!");
        //Start Timer
        new PrintingA(5);
    } else if (isNowMoving){
        System.out.println("MouseMoving");

        //cancel timer & reset ready to start
    }
    public class PrintingA {
        Timer timer;

        public PrintingA(int seconds) {
            timer = new Timer();
            timer.schedule(new PrintingTask(), seconds * 1000);
        }

        class PrintingTask extends TimerTask{
            @Override
            public void run() {
                System.out.println("A");
                timer.cancel();
            }       
        }
    }
}

【问题讨论】:

  • 你读过Timer的文档吗?你了解它的每个方法的作用吗?
  • 您好,您的方法不合适。你是如何预测鼠标空闲的?
  • @vels4j 我有一个与 javaFX mouseMoved 事件相关联的事件侦听器,该事件会根据状态生成布尔值 isMouseMoving。有什么更好的方法?

标签: java timer


【解决方案1】:

我不确定这对您的要求是否有用,Timer 是一种线程工具,用于安排任务以供将来在后台线程中执行。任务可以安排为一次性执行,或定期重复执行。

阅读java文档:java.util.Timer

我更喜欢为 IdleMonitor 设置一个线程并使用Apache Stopwatch 来监控空闲时间。

import org.apache.commons.lang3.time.StopWatch;

public class IdleMonitor implements Runnable {

StopWatch stopWatch;
private final Object monitorObj = new Object();
private boolean isActive;
private long waitTime = 6000; //in milliseconds, put appropriate time to wait

public IdleMonitor() {
    isActive = true;
    stopWatch = new StopWatch();
}

public void reset() { // call this during MouseMoving event
    synchronized (monitorObj) {
        stopWatch.reset();
        monitorObj.notify();
    }
}

public void finish() { // finish idle mointor operation once your operation ends, this will stop the thread
    isActive = false;
    reset();
}

public void start() { // start monitoring
    Thread t = new Thread(IdleMonitor.this);
    t.start();
}

@Override
public void run() {
    synchronized (monitorObj) {
        stopWatch.start();
        while (isActive) {
            try {
                monitorObj.wait(waitTime);
            } catch (InterruptedException ex) {
            }
            long idleTime = stopWatch.getTime();
            System.out.println("Idle time " + idleTime);
            // do something if idle time beyond your expected idle time.
            // you could set isActive=false; if you want to stop monitoring
        }
    }
   }
  }

  }

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    相关资源
    最近更新 更多