SpringBoot中使用@Scheduled创建定时任务

一,在pom.xml文件中加入依赖

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

二,创建启动类上添加注解@SpringBootApplication@EnableScheduling

@SpringBootApplication
@EnableCaching
@EnableScheduling
public class SpringApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringApplication.class, args);

    }
}

三,创建类ScheduledTask用来演示定时任务

使用@scheduled注解来演示定时执行任务的方式
我们通过@scheduled注解用来配置到方法上来完成对应的定时任务的配置,如执行时间,间隔时间,延迟时间等等,下面我们就来详细的看下对应的属性配置。
@Component这个注解可以在程序启动时自动将该类加载进来

fixedDelay属性

该属性是程序启动后每3000ms执行一次

@Component
public class ScheduledTask {

    @Autowired
    public QuartzJobService quartzJobService;

    private static int count1=1;
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Scheduled(fixedDelay = 3000)
    public void fixedDelay() {
        System.out.println(String.format("第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date(System.currentTimeMillis()))));
    }

}

cron属性

推荐一个在线Cron表达式生成器http://cron.qqe2.com/

几个简单例子

fixedRate属性

该属性的含义是上一个调用开始后再次调用的延时(不用等待上一次调用完成),这样就会存在重复执行的问题,所以不是建议使用,但数据量如果不大时在配置的间隔时间内可以执行完也是可以使用的。

@Scheduled(fixedRate = 1000)
    public void fixedRate() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println(String.format("1第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date(System.currentTimeMillis()))));
    }
initialDelay属性

该属性的作用是第一次执行延迟时间

 @Scheduled(initialDelay=1000,fixedDelay = 3000)
    public void initialDelay() {
        System.out.println(String.format("1第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date(System.currentTimeMillis()))));
    }
01-24 06:02
查看更多