1

I'm trying to close a SWT application after certain period of inactive time. I'm finding difficulty in calculating the inactivity period.All that I've tried just shuts the application after the specified amount of time, irrespective of whether I'm still working on the Application.

Below is the code of what I've tried

    Timer timer = new Timer();
    display.asyncExec(new Runnable(){
        public void run() {
            while(!shell.isDisposed()){
                if (!display.readAndDispatch()){ //if the system is idle

                    timer.schedule(new TimerTask() { //schedule timer which will trigger after 1min.

                        @Override
                        public void run() {
                            logout();
                        }
                    }, 60000);

                }
                else{    // reschedule the timer
                    timer.cancel();
                    Timer timer = new Timer();
                }
            }
        }
    });

with this I'm just able to logout after 1 min even if the user is performing something. Is there a way we can check the inactivity time in SWT ?

1
  • 1
    Maybe use Display.addFilter to listen to the various events that you consider are 'activity' and maintain a last active time.
    – greg-449
    May 22, 2019 at 10:47

1 Answer 1

2

You can use Display.addFilter to listen for various events that make the app 'active'. Use Display.timerExec to run code in the UI thread repeatedly to check the time since the last event.

Maybe something like:

private Instant lastActive;

....

   lastActive = Instant.now();

   final Listener listener = new Listener()
    {
      @Override
      public void handleEvent(final Event event)
      {
        lastActive = Instant.now();
      }
    };

   display.addFilter(SWT.MouseMove, listener);
   display.addFilter(SWT.KeyDown, listener);
   // TODO more filters if required

   final Runnable timer = new Runnable()
    {
      @Override
      public void run()
      {
        final Instant now = Instant.now();

        if (ChronoUnit.SECONDS.between(lastActive, now) > xxx) {  // Number of inactive seconds here
          System.out.println("inactive");  // Inactive code here
        }
        else {
          display.timerExec(1000, this);
        }
      }
    };

   display.timerExec(1000, timer);

   ... create/open shell ...

   while (!shell.isDisposed())
    {
      if (!display.readAndDispatch())
        display.sleep();
    }
1
  • Sir, you are awesome.
    – Sambit
    May 22, 2019 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.