SpringBoot定时任务配置及遇到的问题
在springboot中遇到的问题笔记
目录
注解配置
创建定时任务执行类,配置定时任务注解@Scheduled
springboot可以很方便通过注解配置定时任务,不需要配置文件
@Component
public class ScheduledTask {
@Autowired
private CarDataService carDataService;
//定时任务注解,表示每30秒执行一次
@Scheduled(cron = "0/30 * * * * *")
public void entranceScheduled() {
log.info(">>>>>定时任务开始 时间{}", Timestamp.valueOf(LocalDateTime.now()));
//要捕获异常,不然发生异常后定时任务将不再执行
try {
carDataService.carCheckInTask();
} catch (Exception e) {
log.info(">>>任务执行失败 时间{} 错误信息", Timestamp.valueOf(LocalDateTime.now()), e.getMessage());
}
log.info(">>>>>时间任务结束 时间{}", Timestamp.valueOf(LocalDateTime.now()));
}
}
讲讲cron表达式
java中cron表达式是7位,从左到右依次为秒,分,时,日,月,周,年.
- 星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。
- 逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”
- 中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”
- 正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。
* * * * * * *
- - - - - - -
| | | | | | |
| | | | | | + year [optional]
| | | | | +----- day of week (0 - 7) (Sunday=0 or 7)
| | | | +---------- month (1 - 12)
| | | +--------------- day of month (1 - 31)
| | +-------------------- hour (0 - 23)
| +------------------------- min (0 - 59)
+------------------------------ second (0 - 59)
注意事项
- 配置定时任务,application一定要加@EnableScheduling注解才能执行
@SpringBootApplication
@EnableScheduling
public class ParkingDataDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ParkingDataDemoApplication.class, args);
}
}
- 定时任务默认是单个线程执行,若要多线程执行需创建ScheduledThreadPoolExecutor线程池
@Component
@Configuration
public class ScheduledTask implements SchedulingConfigurer {
//创建一个定时任务线程池
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//设定一个长度5的定时任务线程池
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);
scheduledTaskRegistrar.setScheduler(scheduledThreadPoolExecutor);
}
}
定时任务需要添加
try catch
如果定时任务执行过程中遇到发生异常,则后面的任务将不再执行,会出现定时任务执行一段时间不执行的情况.