springBoot系列之定时任务

目录

@EnableScheduling

@Scheduled

cron表达式

常用的cron表达式


 引入pom依赖

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

@EnableScheduling

@EnableScheduling:作用在启动类上表示开启定时任务,如果没有在启动类上添加就不会启动定时任务

第一:启动类添加@EnableScheduling

package com.wxy.rabbit;

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

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

@Scheduled

@Scheduled作用在方法上表示要执行的定时任务的方法

第二:定时任务方法添加@Scheduled

package com.wxy.rabbit.service.Impl;

import com.wxy.rabbit.service.FixedTimeService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class FixedTimeServiceImp implements FixedTimeService {

    @Scheduled(cron= "0/3 * * * * ?")
    @Override
    public void getTimingResult() {
        System.out.println("每隔三秒发送一次");
    }
}

cron表达式

逗号:表示枚举(可以指定任意的时间)

    @Scheduled(cron= "0,1,2,3 * * * * ?")
    @Override
    public void getTimingResult() {
        System.out.println("在每分钟的第一秒,第二秒,第三秒各执行一次");
    }

横线:表示间隔(连续的时间)

  @Scheduled(cron= "0-3 * * * * ?")
    @Override
    public void getTimingResult() {
        System.out.println("在每分钟的第一秒,第二秒,第三秒各执行一次");
    }

星号:表示任意

 @Scheduled(cron= "3 * * * * ?")
    @Override
    public void getTimingResult() {
        System.out.println("在每分钟的第三秒执行");
    }

斜杠:表示步长

    @Scheduled(cron= "0/3 * * * * ?")
    @Override
    public void getTimingResult() {
        System.out.println("每隔三秒发送一次");
    }

问号:主要处理月中的天和周关系,如果定义了其中的一个,另外一个用?表示

常用的cron表达式

每周下午两点执行:cron= "0 0 14 ? * 2"

每天12点执行一次:cron= "0 0 12 * * ?"

每天10点30执行一次:cron="00 30 10 * * ?"

每周一10点半执行一次:cron="00 30 10 ? * 2

每月15号10点半执行一次:cron="00 30 10 15 * ?"

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值