简体   繁体   English

如何在一段时间后启动代码?

[英]How to launch code after an amount of time?

I 'm listening rs232Com using Portcom event-listener then generating propertychangelistener for interface controllers and everything works fine.我正在使用 Portcom 事件侦听器侦听 rs232Com,然后为接口控制器生成 propertychangelistener,一切正常。

My new problem is that acquisitions for some sensors (anemometer) can terminate without any particular indication ( Pulse response ) and mostly dependent of bearings used.我的新问题是某些传感器(风速计)的采集可以在没有任何特定指示(脉冲响应)的情况下终止,并且主要取决于所使用的轴承。

The only solution i can see is that after an amount of time without anymore acquisition ( 2000ms ) i would like to end records to avoid recording data due to involuntary sensor handling .我能看到的唯一解决方案是,在一段时间后不再进行采集(2000 毫秒)后,我想结束记录以避免由于传感器无意识处理而记录数据。

At this point i can stop acquisitions unregistering controller of new message listener list using a button but i would like to do that automatically.在这一点上,我可以使用按钮停止获取取消注册新消息侦听器列表的控制器,但我想自动执行此操作。

The point that miss me is to create a Timer that could launch a task after his delay timed out.This with a re-init function to feed him at each acquisition, barely the same way a watchdog works.想念我的一点是创建一个 Timer 可以在他的延迟超时后启动任务。这具有重新初始化功能,在每次获取时为他提供数据,与看门狗的工作方式几乎相同。

I started to search on web but i didn't find solutions and moreover which direction to go to我开始在网上搜索,但我没有找到解决方案,而且没有找到去哪个方向

-Timer class -Using a Thread / Runnable -Timer 类 - 使用线程/可运行
-Schedule -Modified watchdog -Schedule -Modified 看门狗

Thanks in advance提前致谢

For this kind of problem, I often go with a custom thread that has a timer as attribute.对于此类问题,我经常使用具有计时器作为属性的自定义线程。 The thread check its timer regularly and do something when it ends.线程定期检查它的计时器并在它结束时做一些事情。 And in my main I can add time to the timer attribute if I need to continue.在我的主要内容中,如果需要继续,我可以向计时器属性添加时间。

 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM