SpringBoot创建一个定时任务

大家好,我是猿猴小冷,今天给大家分享SpringBoot怎么创建定时任务

  1. 创建一个定时任务实现类
	package com.lq.x_admin.scheduled;

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

@Component
public class ScheduledTest {
	//每间隔2秒执行一次
    @Scheduled(cron = "*/2 * * * * ?")
    public void runScheduled(){
        Thread current=new Thread();
        System.out.println("定时任务:"+current.getId());
    }
}

2 开启定时任务

package com.lq.x_admin;

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

@SpringBootApplication
@EnableScheduling //开启定时任务
public class XAdminApplication {

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

}
  1. 运行效果图
    在这里插入图片描述

  2. 注解说明:

@Component
将类注入到Spring容器中,相当于注入

@Scheduled
给指定方法添加定时任务

cron
cron表达式由67个空格分隔的时间字段组成:秒 分钟 小时 日期 月份 星期 年(可选)

@EnableScheduling
开启定时任务
  1. 通配符说明:

* 表示所有值. 例如:在分的字段上设置 “*,表示每一分钟都会触发

? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。

例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为"?" 具体设置为 0 0 0 10 * ?

- 表示区间。例如 在小时上设置 “10-12,表示 10,11,12点都会触发。

, 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发

/ 用于递增触发。如在秒上面设置"5/15" 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。

我的分享到此结束,我是猿猴小冷,谢谢大家!

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值