'Java springboot application I have to create in which I have to send requests to multiple endpoint with their schedule time at once
Explanation - I have IP address/port and thier time frequency saved in DB.
I have to create service or job that will run on scheduled time. It will read endpoints from db and send request to each endpoint at same time.
Example data:
10.20.30.111/8890 and time frequency 5 min
10.30.40.112/6764 and time frequency 2 min
Means that i have to create service that will send request to 10.20.30.111/8890
every 5 min and 10.30.40.112/6764
to every 2 min.
How can I create that Service that will run based on different time frequency and send request to multiple endpoints at same time.
Solution 1:[1]
You can inject a TaskScheduler into a configuration class of your application. Assuming that all schedule-related records of (endpoint, frequency) are already (or can be) read from the database, you can translate each of these records to a calls to TaskScheduler.scheduleAtFixedRate
(converting the frequency to interval of type Duration
).
For example, a skeleton would be:
@Configuration
@EnableScheduling
public class Question72238004Config
{
// represents the database repository for tasks FooTask
@Autowired
FooTaskRepository fooTaskRepository;
@Bean
public TaskScheduler taskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
// configure task scheduler ...
scheduler.setPoolSize(2);
return scheduler;
}
@PostConstruct
void setup()
{
final TaskScheduler scheduler = this.taskScheduler();
// Read records of (endpoint,freq) from fooTaskRepository
for (FooTaskEntity t: fooTaskRepository.findAll()) {
// extract endpoint from t, build a Runnable from it
Runnable r = ... ;
// extract frequency and transform to Duration
Duration d = Duration.ofMinutes(...);
// Schedule
scheduler.scheduleAtFixedRate(r, d);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Michail Alexakis |