# SpringBoot定时任务——Scheduled定时任务器

SpringBoot定时任务——Scheduled定时任务器


Scheduled定时任务器

Scheduled定时任务器:是Spring3.0以后自带的定时任务器

导入相关依赖
  • pom.xml,Springboot的Web启动器中没有包含Scheduled的相关的jar包,所以 要添加相关的依赖
<!-- 添加Scheduled依赖    -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
写定时任务方法

@Scheduled注解设置定时任务方法,用Cron表达式触发定时任务方法

@Component
public class ScheduledDemo {
    /**
     * Scheduled定时任务
     */
    @Scheduled(cron = "0/1 * * * * ?")
    public void scheduledMethod(){
        System.out.println("我是一个定时任务"+new Date());
    }
}
启动类中开启定时任务的启动

SpringBoot默认定时任务是关闭的,使用@EnableScheduling注解进行开启定时任务的操作。

@SpringBootApplication
@EnableScheduling
public class TaskCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(TaskCenterApplication.class);
    }
}

在这里插入图片描述
使用比较简单。

Cron表达式

基于字符串的一种对时间的规定格式,分为6域和7域。日要搭配月否则会出错

语法
位置时间域名允许值
10-59
2分钟0-59
3小时0-23
41-31
51-12
6星期1-7
7年(可选)1970-2099
3 * * * * * ?	#每分钟的第3秒触发
3 50 18 31 * ? 	# 每个月的31号18:50:03秒执行任务
3 50 18 * 3 4	 #3月份的每个星期3 18:50:03秒执行任务
10,15 * 18 * 2 ?	#2月份的每一天的18点的每分钟的第10和第15秒执行任务
0/1 * * * * * 	#间隔1秒执行任务
  • *:表示任意一个。

  • ?:表示占位符号没有实际意义

  • -:表示范围内的。

  • ,:表示列表值

  • #:间隔1秒执行任务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值