springboot使用@Scheduled定时器任务

1、在springboot启动类中设置启用定时任务功能,添加注解 @EnableScheduling

package com.jeff;

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

@SpringBootApplication
@EnableScheduling
public class JfSpringbootApplication {

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

}

注:@EnableScheduling 注解的作用是发现注解:@Scheduled的任务并后台执行
2、创建测试类(TestScheduler.java)

package com.jeff.timer;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * @author Jeff
 * @description 定时器任务
 * @date 2019/10/29
 */
@Component
public class TestScheduler {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //每隔2秒执行一次
    @Scheduled(fixedRate = 2000)
    public void testTasks1() {
        System.out.println("fixedRate定时任务执行时间:" + dateFormat.format(new Date()));
    }

    //每隔10秒执行一次
    @Scheduled(cron = "0/5 * * * * ? ")
    public void testTasks2() {
        System.out.println("cron定时任务执行时间:" + dateFormat.format(new Date()));
    }

}

注: 需要在定时任务的类上加上注解:@Component,在具体的定时任务方法上加上注解:@Scheduled,即可启动该定时任务
3、控制台输出结果
在这里插入图片描述

@Scheduled参数描述

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

源码地址

https://gitee.com/jiefu813/jf-springboot/tree/jf_Scheduled/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值