12.Springboot 之 使用Scheduled做定时任务

来源:互联网 发布:什么软件可以升级win10 编辑:程序博客网 时间:2024/06/08 13:30
本文所属【知识林】:http://www.zslin.com/web/article/detail/21

在定时任务中一般有两种情况:

  1. 指定何时执行任务
  2. 指定多长时间后执行任务

这两种情况在Springboot中使用Scheduled都比较简单的就能实现了。

  • 修改程序入口
@SpringBootApplication@EnableSchedulingpublic class RootApplication {    public static void main(String [] args) {        SpringApplication.run(RootApplication.class, args);    }}

在程序入口的类上加上注释@EnableScheduling即可开启定时任务。

  • 编写定时任务类
@Componentpublic class MyTimer {    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");    @Scheduled(fixedRate = 3000)    public void timerRate() {        System.out.println(sdf.format(new Date()));    }}

在程序启动后控制台将每隔3秒输入一次当前时间,如:

23:08:4823:08:5123:08:54

注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任务。

下面描述下@Scheduled中的参数:

@Scheduled(fixedRate=3000):上一次开始执行时间点3秒再次执行;

@Scheduled(fixedDelay=3000):上一次执行完毕时间点3秒再次执行;

@Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次执行完毕时间点后3秒再次执行;

@Scheduled(cron="* * * * * ?"):按cron规则执行。

下面贴出完整的例子:

package com.zslin.timers;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by 钟述林 393156105@qq.com on 2016/10/22 21:53. */@Componentpublic class MyTimer {    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");    //每3秒执行一次    @Scheduled(fixedRate = 3000)    public void timerRate() {        System.out.println(sdf.format(new Date()));    }    //第一次延迟1秒执行,当执行完后3秒再执行    @Scheduled(initialDelay = 1000, fixedDelay = 3000)    public void timerInit() {        System.out.println("init : "+sdf.format(new Date()));    }    //每天23点27分50秒时执行    @Scheduled(cron = "50 27 23 * * ?")    public void timerCron() {        System.out.println("current time : "+ sdf.format(new Date()));    }}

在Springboot中使用Scheduled来做定时任务比较简单,希望这个例子能有所帮助!

0 0