Search code examples
javascheduled-tasksquarkusstopwatch

Java permanently running Task to check time


I have written a task that runs as Scheduled (every Second). I need this scheduled method to monitor the lifetime of a bearer token.

I'm new to Java and wondering if there isn't a better, more elegant solution. I didn't find anything suitable using the search. Maybe I also used the wrong terms.

I used: StopWatch (org.apache.commons commons-lang3 Version 3.13.0) To build and test, I use Maven and Quarkus. (io.quarkus.scheduler.Scheduled)

My Scheduled Method:

@Scheduled(every = "1s")
    public void checkStopuhr() {
        if (stopwatch.isStarted() && (stopwatch.getTime() / 1000) >= maxLifetimeBearerToken) {
            try {
                //System.out.println("Stopuhr vor reset: " + stopwatch.getTime());
                refreshBearer(clientAppId);
            } catch (IOException e) {
                logger.atError().log("Error Methode: ServiceTokenImpl.checkStopuhr(), Fehler beim Erstellen eines neuen Bearer-Tokens.");
            }
        } else if(stopwatch.isStarted() && (stopwatch.getTime()/1000) > (maxLifetimeBearerToken + 1)){
            logger.atWarn().log("Die Stopuhr funktioniert nicht richtig. Sie wurde ausgelöst bei {} Sekunden",stopwatch.getTime()/1000);

        } else {
            if(stopwatch.isStarted()){
                System.out.println("verstrichene Zeit = " +stopwatch.getTime()/1000);
            }
        }
    }

Maybe one of you has a good idea that is understandable for me as a beginner?


Solution

  • Since you know the lifetime of the token, you can schedule a one time task to refresh it at the right time. I'll use java's scheduler to demonstrate the logic, it should be fairly easy to translate to the framework you are using.

    //get the token
    long maxLifetimeBearerToken = //get validity from token
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    Runnable refreshTokenAction = () -> {
      //refresh the token
      //register next task
    };
    service.schedule(refreshTokenAction, maxLifetimeBearerToken, TimeUnit.MILLISECONDS);//or other timeunit, depending on what is maxLifetimeBearerToken
    

    This uses ScheduledExecutorService.submit() to register a task for single execution:

    Submits a one-shot task that becomes enabled after the given delay.