Inactivity Timeout

Inactivity Timeout

Question:
I’d like incorporate an inactivity timeout for an application.When there is no mouse or keyboard activity in the application fora certain period of time, I want to close all the windows and dialogsof the application.

Answer:
The easiest way to implement an inactivity timeout is to keep track ofthe last time a MouseEvent or KeyEvent was sent to an application.In a separate thread, set a timer that checks periodically if the difference between the current time and the timestamp is greater than the timeout interval.

The following program demonstrates thistechnique. TimeoutListener keeps track of the last InputEvent sent to the application by implementing MouseListener, MouseMotionListener,and KeyListener. Each time any one of those interface methods iscalled, TimeoutListener records the current time. TimeoutListeneralso implements the ActionListener interface so that it may be usedwith the Swing Timer class.

Every time the Timer expires, it invokesthe actionPerformed method in its registered ActionListener.TimeoutListener calculates the difference between the the lastrecorded time and the current time when this happens. If it isgreater than the timeout value, it exits. The Timer class may beactive in a separate thread, so it is necessary to avoid raceconditions by protecting the time recording and testing with asynchronized block.

The problem with this approach is that it is slightly inaccurate dueto the polling. The actual inactivity timeout will be a value betweenthe specified timeout and the timeout plus the polling period. Toobtain a more accurate timeout, you can forego polling, set the Timerdelay to the timeout value, and restart the Timer every time an eventis delivered. When the timer expires, have its ActionListener exitthe application. This approach may have a higher overhead becauserestarting the Swing Timer involves removing the timer from a queueand adding it again in addition to cancelling pending firings.

import java.awt.*;import java.awt.event.*;import javax.swing.*;class TimeoutListener implements MouseListener,				 MouseMotionListener,				 KeyListener, ActionListener{  Object _lock;  long _timeout, _lastTime;  public TimeoutListener(long timeout) {    _lock     = new int[1];    _timeout  = timeout;    _lastTime = System.currentTimeMillis();  }  private void __recordLastEvent(InputEvent event) {    synchronized(_lock) {      _lastTime = System.currentTimeMillis();      System.out.println("Last Event: " + _lastTime + " " + event);    }  }  public void actionPerformed(ActionEvent e) {    synchronized(_lock) {

We really shouldn’t exit, but cleanup gracefully instead

      if(System.currentTimeMillis() - _lastTime >= _timeout) {	System.out.println("Timed out! " + System.currentTimeMillis());	System.exit(0);      } else	System.out.println("Still active.");    }  }  public void mouseDragged(MouseEvent e) { __recordLastEvent(e); }  public void mouseMoved(MouseEvent e)   { __recordLastEvent(e); }  public void mouseClicked(MouseEvent e) { __recordLastEvent(e); }  public void mouseEntered(MouseEvent e) { __recordLastEvent(e); }  public void mouseExited(MouseEvent e)  { __recordLastEvent(e); }  public void mousePressed(MouseEvent e) { __recordLastEvent(e); }  public void mouseReleased(MouseEvent e){ __recordLastEvent(e); }  public void keyPressed(KeyEvent e)     { __recordLastEvent(e); }  public void keyReleased(KeyEvent e)    { __recordLastEvent(e); }  public void keyTyped(KeyEvent e)       { __recordLastEvent(e); }}public class Timeout {  public static final int TIMEOUT = 10000;  // milliseconds  public static void main(String[] args) {    Frame frame = new Frame("Progress Demo");    WindowListener exitListener;    TimeoutListener timeoutListener;    Timer timer;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };    timeoutListener = new TimeoutListener(TIMEOUT);    frame.addMouseListener(timeoutListener);    frame.addMouseMotionListener(timeoutListener);    frame.addKeyListener(timeoutListener);    frame.addWindowListener(exitListener);    frame.setSize(400, 400);    frame.setVisible(true);

We poll at half the timeout interval to reduce the fudge factor introduced by events delivered at just under the timeout value.

    timer = new Timer(TIMEOUT / 2, timeoutListener);    timer.setRepeats(true);    timer.start();  }}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes