Spring Boot - infinite loop service

前端 未结 3 1096
旧时难觅i
旧时难觅i 2021-02-09 14:27

I want to build a headless application which will query the DB in infinite loop and perform some operations in certain conditions (e.g. fetch records with specific values and wh

3条回答
  •  遥遥无期
    2021-02-09 14:56

    There are several options. My approach is to start a loop on an ApplicationReadyEvent, and abstract away the loop logic into an injectable service. In my case it was a game loop, but this pattern should work for you as well.

    package com.ryanp102694.gameserver;
    
    import com.ryanp102694.gameserver.service.GameProcessor;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.event.ApplicationReadyEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.stereotype.Component;
    
    @Component
    public class GameLauncher implements ApplicationListener {
        private static Logger logger = LoggerFactory.getLogger(GameLauncher.class);
    
        private GameProcessor gameProcessor;
    
        @Autowired
        public GameLauncher(GameProcessor gameProcessor){
            this.gameProcessor = gameProcessor;
        }
    
        @Override
        public void onApplicationEvent(ApplicationReadyEvent event) {
            logger.info("Starting game process.");
            gameProcessor.start();
            while(gameProcessor.isRunning()){
                logger.debug("Collecting user input.");
                gameProcessor.collectInput();
                logger.debug("Calculating next game state.");
                gameProcessor.nextGameState();
                logger.debug("Updating clients.");
                gameProcessor.updateClients();
            }
            logger.info("Stopping game process.");
            gameProcessor.stop();
        }
    }
    
    

提交回复
热议问题