使用Spring的定时任务

使用@Scheduled注解可以使用Spring提供的自动定时任务,通过以下几步即可实现通过Spring提供的自动任务来自动执行我们的程序。

首先需要**引入**task的命名空间

xmlns:task="http://www.springframework.org/schema/task"

然后在Spring的配置文件中配置**开启**Spring的自动任务功能

<!--不使用线程池的用法-->
<task:annotation-driven/>
<!-- 使用线程池的用法,据说不配置线程池在多任务时存在问题,未深究 -->
<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="5"/>

使用@Scheduled来标注需要自动执行的函数

/*为了方便配置,将cron表达式放置在config.properties中,然后在代码中引用,当然如果不需要配置也可以直接写在代码中*/
@Scheduled(cron="${push.billCheck.interval}")
public void execute(){
    Date checkDate = DateUtil.beforeDays(DateUtil.getNow(), 1);
    accountChangeBillCheck(checkDate);
}

注意:

  • 要使用@Scheduled你的Bean需要交由Spring托管;
  • @Scheduled除了cron还支持fixedDelayfixedRate两个参数,从字面来看应该是为自动任务设置一个固定延时和一个固定的执行周期,我没有深入了解,因为cron已经能够满足绝大部分需求了;
  • @Scheduled标注的函数需要满足1.没有参数,2.没有返回值

config.properties

push.billCheck.interval=0 09 14 * * ?

通过以上几个步骤,就可以实现Spring的自动任务了。

猜你喜欢

转载自blog.csdn.net/d578332749/article/details/81286544
今日推荐