在企业应用中,常常需要在Web请求中添加后续处理,或是执行一些定时启动的任务,比如:定时清理零时表…, Spring Boot为这类型的任务提供了良好的支持,开发起来非常方便。

定义异步任务

要定义一个异步执行的任务只需要在容器管理的Bean中对方法加上@Async即可。最常见的方法是将一个任务定义为一个容器管理的Bean,用@Component 进行注解,然后将要执行的方法用@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);
}
}
}

然后可以在适当的地方进行调用,比如在业务层代码中进行调用,则可写为:

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

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

定义定时执行的任务

定义一个容器管理的Bean,在其中的方法定义为定时执行:

固定间隔时间执行

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);
}
}

用Cron语法配置定时

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);
}
}

以上代码为每分钟执行一次。

TAGS