how to call a method automatically in every seconds using spring boot?

Viewed 8096

In Spring-boot project, is there a method that want to make it called every seconds automatically?

And make an rest-api to set calling term in same project?

2 Answers

Here comes an example.
The greeting method will be executed every 5 seconds and it can be called when you visit /hello endpoint.

@SpringBootApplication
@EnableScheduling
@RestController
public class So47301079 {
    public static void main(String[] args) {
        SpringApplication.run(So47301079.class, args);
    }

    @Scheduled(fixedRate = 5000)
    @GetMapping(value="/hello")
    public void greeting() {
        System.out.println("Hello!!!");
    }
}

Hope this helps you!

Can use cron expression like @Scheduled(cron="*/5 * * * * *"). In this way, we have a control on minutes, hours, days also. Have a look at this video to know different possible ways to use cron expression.

Related