Search code examples
javamultithreadingjavafxdaemonrunnable

Keep Java Thread running all the time


Looking for an elegant way to keep a Java thread running all the time in the background, as long as the application is running, for a JavaFX app checking to see is the User Credentials are valid or not. What I would be doing inside the Thread is expiring the users after certain interval


Solution

  • If you want to timeout the login you can use a PauseTransition to expire the login:

    Duration timeout = Duration.minutes(...);
    PauseTransition logoutTimer = new PauseTransition(timeout);
    logoutTimer.setOnFinished(e -> expireCredentials());
    logoutTimer.play();
    

    If you need to reset the timeout at any point, you can just do

    logoutTimer.playFromStart();
    

    and it will reset the timer.

    You can also use JavaFX properties to make this easy to manage in the application. E.g.

    private BooleanProperty loggedIn = new SimpleBooleanProperty();
    
    // ...
    
    public void expireCredentials() {
        loggedIn.set(false);
    }
    

    Then operations which require the user to be logged in can check this property:

    if (loggedIn.get()) {
        doSecureOperation();
    }
    

    and UI controls can bind their states to it:

    submitSecureDataButton.disableProperty().bind(loggedIn.not());
    loginButton.disableProperty().bind(loggedIn);
    

    or perhaps

    private ObjectProperty<Credentials> credentials = new SimpleObjectProperty<>();
    
    // ...
    
    public void expireCredentials() {
        credentials.set(null);
    }
    
    // ...
    
    submitSecureDataButton.disableProperty().bind(credentials.isNull());
    loginButton.disableProperty().bind(credentials.isNotNull());