有时我们需要创建定时任务,自动执行指定的业务逻辑。在Springboot中最简单的方式是使用注解Scheduled来创建定时任务。以下介绍具体实现步骤。

一、添加注解

首先需要在方法类的声明部分,添加注解@EnableScheduling,并且将类声明为Service类,以便程序运行后自动加载该类。

@Service
@Configuration
@EnableScheduling
public class SyncServImpl {
private static Log log = LogFactory.getLog(SyncServImpl.class);

@Scheduled(cron = "${cron.report.shoucash}")
public void takeShoucash() {
log.info("定时任务开始..");
try {
rpShoucashDAO.add(map);//执行业务逻辑
} catch (Exception e) {
log.error(e);
}
}

二、设置定时

上文中的定时时间${cron.report.shoucash}是读取application*.yml的配置,设定了每5分钟执行一次。代码如下:

cron:
report:
shoucash: 0 0/5 * * * ? #生成催缴数据

运行程序后,程序正常会在5分钟执行一次takeShoucash方法。