【问题标题】:How to launch code after an amount of time?如何在一段时间后启动代码?
【发布时间】:2021-10-27 12:07:41
【问题描述】:

我正在使用 Portcom 事件监听器监听 rs232Com,然后为接口控制器生成 propertychangelistener,一切正常。

我的新问题是某些传感器(风速计)的采集可能会在没有任何特定指示(脉冲响应)的情况下终止,并且主要取决于所使用的轴承。

我能看到的唯一解决方案是,在一段时间内不再进行采集(2000 毫秒)后,我想结束记录,以避免由于非自愿的传感器处理而记录数据。

此时我可以使用按钮停止获取注销新消息侦听器列表的控制器,但我想自动执行此操作。

想念我的一点是创建一个计时器,它可以在他的延迟超时后启动一个任务。这带有一个重新初始化功能,可以在每次采集时为他提供数据,几乎与看门狗的工作方式相同。

我开始在网上搜索,但我没有找到解决方案,而且我应该去哪个方向

-定时器类 - 使用线程/可运行
-日程 -修改后的看门狗

提前致谢

【问题讨论】:

  • 我不太明白你的问题,但是如果你想暂停一段时间你应该使用TimeUnit.SECONDS.sleep(1);或TimeUnit.MINUTES.sleep(1);
  • 正如 Jean-Marc Jancovici 常说的“当你不理解一个问题时,你认为解决方案就是从帽子里汲取灵感”

标签: java timer schedule watchdog


【解决方案1】:

对于此类问题,我经常使用具有计时器作为属性的自定义线程。线程定期检查它的计时器,并在它结束时做一些事情。如果需要继续,我可以在我的 main 中为 timer 属性添加时间。

 private static class CustomThread extends Thread {
    private static int wait = 1000;
    private int timer = 0;
    
    public DeleteThread(int timer) {
        this.timer = timer;
    }
    
    public void addToTimer(int time) {
        this.timer += time;
    }

    public void run() {
        while(this.timer > 0) {
            try {
                Thread.sleep(wait);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.timer -= wait;
        }
        
        //timer as ended
        doSomething();
    }
}

public class Main {
    public static void main(String[] args) {
        CustomThread myThread = new CustomThread(2000);
        myThread.start();

        //someCode

        //Here I need my thread to continue for 1000 more
        myThread.addToTimer(1000);
    }
}

【讨论】:

  • 谢谢! je l'ai passé en runnable et ajouté une progressBar , mais c'est exactement la base que je cherchais
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多