Timeouts

Categories: ,
Tags:

Timeouts are often required. JANOS supports timeouts on most inputs. Sometimes though you just need to implement an overall timeout. For example, if you leave an UI unattended for some period of time you might want it to return to a default Splash Screen or something along those lines.

This is easily achieved and we usually use the uptime in milliseconds as a reference. The approach is to add the timeout period to the current uptime and when the uptime exceeds that perform the timeout action. In the meantime if events occur (such as UI leypad activity) you reset the tmeout by recalculating.

Here is example code:

public class Main {
    
    static final int TIMEOUT = 120000;
    
    public static void main(String[] args) throws Exception {
        
        // Print time
        System.out.println(new Date());
        
        // establish and initialize a timeout
        long timer = JANOS.uptimeMillis() + TIMEOUT;
        
        while (JANOS.uptimeMillis() < timer) {
            
            // some event would reset the timer
            // timer = JANOS.uptimeMillis() + TIMEOUT;
            
            System.sleep(1000);
        }
        
        System.out.println("Timeout expired.");
        System.out.println(new Date());
    }
        
}
bruce_dev /> jtest
Wed Dec 06 09:16:31 EST 2017
Timeout expired.
Wed Dec 06 09:18:32 EST 2017

bruce_dev />

And there you go. Close enough to 2 minutes (120000 milliseconds). Typically such timeouts need not be precise. You do not want to load the CPU doing little else than checking for timeout. If you are trying to implement an accurate delay or scheduling an event at a precise time there are other approaches. This is your quick and dirty timeout.

Note that you do not want to use the RTC time of day for this kind of timeout. That can jump discontinuously when for instance the clock is adjusted manually or through the NTP protocol.

Categorised in: ,

This post was written by Bruce Cloutier

December 6, 2017 10:21 am