Spring boot 定时任务

来源:互联网 发布:数据分析挖掘主观题 编辑:程序博客网 时间:2024/05/22 04:46

Spring boot 定时任务

说到定时任务呢,大家应该都很熟悉了,其实定时任务这块确实使用起来没太大变化,主要在spring boot中使用定时任务时需要在启动时将定时任务开启,具体的定时任务实现类添加注解即可,详细说明如下:

1.在启动类中需要添加一个类注释:@EnableScheduling;

2.在job的实现类中添加类注释:@Component和方法注释:@Scheduled(cron="0/10 * * * * ?")

就是这么简单,具体代码如下:

package com.zxl.examples.job;import com.zxl.examples.service.UserSerivceImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * Created by Administrator on 2017/7/27. */@Componentpublic class UserJob {    @Autowired    UserSerivceImpl userSerivce;    @Scheduled(cron="0/10 * * * * ?")    private void printSomething(){        System.out.println("------------------------------this is a test job");    }    @Scheduled(cron="0/10 * * * * ?")    private void callService(){        System.out.println("###############################this is a test job,the call service method value is : "                +userSerivce.canCache());    }    @Scheduled(fixedRate = 10000)    private void printSomething2(){        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^this is a test job2");    }}


小提示:@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate 说明
  ● @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
  ● @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
  ● @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次