目录
引入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 * ?"