Springboot创建定时任务

使用Springboot创建一个定时任务,需要用到的注解为@Scheduled、@EnableScheduling、@Component

譬如,预警定时功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component
public class WarnScheduler {

@Autowired
UserService userService;

@Autowired
UserRepository userRepository;

@Scheduled(fixedRate = 2000)
public void get() {
User user = userRepository.get(1);
System.out.println(user);
}

@Scheduled(fixedRate = 2000)
public void getList() throws JsonProcessingException {
UserParam userParam = new UserParam();
Page<User> users = userRepository.getList(userParam);
System.out.println("GetList:" + new ObjectMapper().writeValueAsString(users));
}
}
1
2
3
4
5
6
7
@SpringBootApplication
@EnableScheduling
public class FinanceScheduleApp {
public static void main(String[] args) {
SpringApplication.run(FinanceScheduleApp.class, args);
}
}

其中@Scheduled中有几个属性设置

cron属性

从左至右分别是 :{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}

例如:

  • "0 0 12 * * ?" 每天中午十二点触发
  • "0 15 10 ? * *" 每天早上10:15触发
  • "0 15 10 * * ?" 每天早上10:15触发
  • "0 15 10 * * ? *" 每天早上10:15触发
  • "0 15 10 * * ? 2005" 2005年的每天早上10:15触发
  • "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
  • "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
  • "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
  • "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
  • "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
  • "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发

fixedRate属性

该属性的含义是上一个调用开始后再次调用的延时(不用等待上一次调用完成),这样就会存在重复执行的问题,所以短时间调用不建议使用

fixedDelay属性

该属性的功效与上面的fixedRate则是相反的,配置了该属性后会等到方法执行完成后延迟配置的时间再次执行该方法。

initialDelay属性

初始化延迟时间设置,项目启动初始化第一次使用该方法所配置的延迟时间

赏个🍗吧
0%