Scheduled Tasks in a Spring Boot Application

In this article, we demostrate how to define the scheduled tasks in a Spring Boot Application.

Why you need scheduled tasks in a Spring Boot application?

In enterprise applications, it is often necessary to add follow-up processing to web requests, or perform some timed tasks, such as: Scheduled cleaning of temporary tables, Scheduled summary of data, etc. Spring Boot provides good support for this type of task, and it is very convenient to develop.

In fact, Spring Boot provides at least two ways to perform scheduled tasks: One is to use @Async annotation, Another is to use @Scheduled annotation.

Use @Async

To define a task that executes asynchronously, all you need to do is to add @Async to the method in the container-managed bean. The most common approach is to define a task as a container-managed bean, annotate it with @Component, and then annotate the method you want to execute with @Async:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class AsyncTask {

private static final Logger LOG = LoggerFactory.getLogger(AsyncTask.class);

@Async
public void sendMessage(String message) {

for (int i = 0; i < 100; i++) {
LOG.info("NO.{} message is: {}", i + 1, message);
}
}
}

Calls can then be made where appropriate, such as in business-layer code, which can be written as:

1
2
3
4
5
6
...
@Autowired
private AsyncTask asyncTask;

...
asyncTask.sendMessage("Hello");

Use @Scheduled

Defines a container-managed Bean in which the method is defined as scheduled execution:

Execution at fixed intervals

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class BackupDBTask {

private static final Logger LOG = LoggerFactory.getLogger(BackupDBTask.class);

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {

long now = System.currentTimeMillis() / 1000;
LOG.info("Execute: backup Database, time = {} ", now);
}
}

Configure timing with Cron syntax

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class BackupDBTask {

private static final Logger LOG = LoggerFactory.getLogger(BackupDBTask.class);

@Scheduled(cron = "0 */1 * * * ?")
public void scheduleTaskUsingCronExpression() {

long now = System.currentTimeMillis() / 1000;
LOG.info(
"schedule tasks using cron jobs - Time = {}", now);
}
}

The above code is executed every minute.

本文标题:Scheduled Tasks in a Spring Boot Application

文章作者:Morning Star

发布时间:2022年01月28日 - 11:01

最后更新:2022年01月28日 - 11:01

原始链接:https://www.mls-tech.info/java/how-to-implement-scheduled-tasks-spring-boot/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。