📜 ⬆️ ⬇️

Scheduled code execution in the Spring Framework

Here itch me to periodically run some code in a small project written in the Spring Framework. I was already prepared for the old memory (since spring 2.x) for a long screwing quartz and writing a heap of configs on xml, as it turned out everything is much simpler

Spring Framework documentation as usual gives an exhaustive, but sometimes redundant answer.

In fact, everything is simple:

1. Do it once - add to your spring configuration (the minimum is present in any project - not everything is still annotated) task namespace that would look something like this (note the word task):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
www.springframework.org/schema/beans www.springframework.org/schema/beans/spring-beans.xsd
www.springframework.org/schema/context www.springframework.org/schema/context/spring-context.xsd
www.springframework.org/schema/tx www.springframework.org/schema/tx/spring-tx.xsd
www.springframework.org/schema/task www.springframework.org/schema/task/spring-task.xsd">

')
2. Do two - in the same place configure the scheduler:

<task:annotation-driven executor="executor" scheduler="scheduler"/>
<task:executor id="executor" pool-size="5"/>
<task:scheduler id="scheduler" pool-size="10"/>


3. Do three - hang the @Scheduled annotation on the method of some bean, for example:
@Scheduled (fixedDelay = 5000)
public void doSomething () {
// do something every 5 seconds
}

Everything! Once again, he was convinced of his love for springing - when technologies are developed not for the sake of technology, but for the convenience of developers

Source: https://habr.com/ru/post/130306/


All Articles