有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果满足特定条件,java是否重置计时器?

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

今天早些时候,我看了一遍,试图找到一个解释和示例,其中详细说明了如何启动、停止/取消和重置计时器,但却被各种不同的方法轰击到尝试并这样做,这让我非常困惑

我正在遵循来自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();
            }       
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我不确定这对你的需求是否有用,计时器是线程安排任务以便在后台线程中执行的工具。任务可以安排为一次性执行,也可以定期重复执行

    阅读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
            }
        }
       }
      }
    
      }