SpringBoot定时器

SpringBoot定时器

@Scheduled:

  • @Scheduled(fixedRate=3000):上一次开始执行时间点后3秒再次执行;
  • @Scheduled(fixedDelay=3000):上一次执行完毕时间点3秒再次执行;
  • @Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次执行完毕时间点3秒再次执行;
  • @Scheduled(cron="* * * * * ?"):按cron规则执行;

@EnableScheduled:发现@Scheduled注解任务并执行

1.首先先创建一个springboot项目
2.在Application设置启动启动定时作用的功能

package com.ytzl.springboot;

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

@SpringBootApplication
@EnableScheduling
public class SpringbootApplication {

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

}

3.创建实现类

package com.ytzl.springboot.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 作者: fyq
 * 时间: 2020/8/21 0021 14:42
 * 描述: 定时器
 */
@Component
@Slf4j
public class Scheduler {
    private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void testTasks(){
        log.info("定时任务执行时间:"+dateFormat.format(new Date()));
    }
    
}

注意:
需要在具体实现类中加上@Componeent注解,其中@Slf4j是日志记录。

4.运行结果:
在这里插入图片描述
还可以设置每天定时执行任务
在实现类中加入以下代码

@Scheduled(cron ="0 19 23 ? * *" )
    public void testTimeTask(){
        //每天23:19整执行一次
        log.info("定时任务执行时间:"+dateFormat.format(new Date()));
    }

运行结果如下:
在这里插入图片描述

cron规则
“*”字符代表所有可能的值(位置不同,取值范围不同)
“/”字符用来指定数值的增量(区间)
“?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值
“L” 字符仅被用于天(月)和天(星期)两个子表达式,即英文单词last

  • 用在月份上:2L表示月份的最后l两天

  • 用在天数上:2L表示这个星期最后两天

    cron表达式中各时间元素即 * ,使用空格进行分割,表达式有至少6个(也可能7个)取值范围为:
    秒(0~59)
    分钟(0~59)
    小时(0~23)
    天(每个月天数,28~31)
    月(0~11)
    天(星期)(1~7 或 SUN,MON,TUE,WED,THU,FRI,SAT)
    年份(1970-2099)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值