SpringBoot 之定时任务

定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。 Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、 TaskScheduler 接口。

使用@EnableScheduling与@Scheduled完成定时任务

(1)@EnableScheduling开启基于注解的定时任务

package com.kuake.spingboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling//开启基于注解的定时任务
@SpringBootApplication
public class SpingbootAsyncApplication {

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

}

(2)@Scheduled来定制定时任务

    /**
     * second  minute, hour, day of month, month , day of week, (year)
     * <p>E.g. {@code "0 * * * * MON-FRI"}
     */
    @Scheduled(cron = "0-10 * * * * *")
    public void myTask(){
        System.out.println("hello==========>当前的线程"+Thread.currentThread().getName());
    }

输出结果:

2019-06-12 15:36:32.281  INFO 8752 --- [           main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2019-06-12 15:36:32.329  INFO 8752 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-06-12 15:36:32.334  INFO 8752 --- [           main] c.k.s.Spingboot04AsyncApplication        : Started Spingboot04AsyncApplication in 5.596 seconds (JVM running for 7.434)
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1

上面@Scheduled配置的cron = 0-10 * * * * *,代表每一分钟的0-10秒执行。现在来介绍一下cron表达式:
cron表达式由7个部分组成,各部分用空格隔开。每个部分代表的含义从左到又分别是 second minute, hour, day of month, month , day of week, (year),最后一个位置年可以省略不写。
也可以使用一些符号来方便我们表达:

字段合法值范围
0-59,-*/
0-59,-*/
0-23,-*/
1-31,-*/ L W C
1-12,-*/
0-7或者 SUN-SAT,-*/ L C #
符号意义
枚举
×整个时段
步长(就是每隔多少)
L最后
C工作日
#星期 (3#2 第三个星期二)

举例个子:
0 0/3 11,12 * * ? 每个月的每一天的 11点 12点 每隔三分钟执行一次
0 0 2-4 ? * 3#1 每个月的 第三周的周一 2 点 到4点 整点执行。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值