Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - infinite loop service

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 when found launch e-mail sending procedure for each message).

I want to use Spring Boot as a base (especially because of Actuator to allow expose health-checks), but for now I used Spring Boot for building REST web-services.

Is there any best practices or patterns to follow when building infinite loop applications ? Does anyone tried to build it based on Spring Boot and can share with me his architecture for this case ?

Best regards.

like image 806
Pawel Urban Avatar asked Apr 11 '16 06:04

Pawel Urban


People also ask

Can a for loop go on forever?

Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }

How do I get out of endless loop?

In order to come out of the infinite loop, we can use the break statement. Let's understand through an example. In the above code, we have defined the while loop, which will execute an infinite number of times until we press the key 'n'. We have added the 'if' statement inside the while loop.

Why is my Java loop infinite?

Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all.

What is infinite loop and how it is declared?

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.


1 Answers

Do not implement an infinite loop yourself. Let the framework handle it using its task execution capabilities:

@Service
public class RecordChecker{

    //Executes each 500 ms
    @Scheduled(fixedRate=500)
    public void checkRecords() {
        //Check states and send mails
    }
}

Don't forget to enable scheduling for your application:

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

See also:

  • Scheduling Tasks
like image 150
Xtreme Biker Avatar answered Sep 17 '22 15:09

Xtreme Biker