springboot(九):定时任务

在咱们的项目开发过程当中,常常须要定时任务来帮助咱们来作一些内容,springboot默认已经帮咱们实行了,只须要添加相应的注解就能够实现spring

一、pom包配置

pom包里面只须要引入springboot starter包便可springboot

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
	</dependency>
</dependencies>

二、启动类启用定时

在启动类上面加上@EnableScheduling便可开启定时spring-boot

@SpringBootApplication
@EnableScheduling
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

三、建立定时任务实现类

定时任务1:this

@Component
public class SchedulerTask {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    private void process(){
        System.out.println("this is scheduler task runing  "+(count++));
    }

}

定时任务2:spa

@Component
public class Scheduler2Task {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("如今时间:" + dateFormat.format(new Date()));
    }

}

结果以下:code

this is scheduler task runing  0
如今时间:09:44:17
this is scheduler task runing  1
如今时间:09:44:23
this is scheduler task runing  2
如今时间:09:44:29
this is scheduler task runing  3
如今时间:09:44:35

参数说明

@Scheduled 参数能够接受两种定时的设置,一种是咱们经常使用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。orm

fixedRate 说明ci

  • @Scheduled(fixedRate = 6000) :上一次开始执行时间点以后6秒再执行
  • @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点以后6秒再执行
  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,以后按fixedRate的规则每6秒执行一次
相关文章
相关标签/搜索