1:Spring的定时任务 —— Spring Task
如果使用的是 Spring 或 Spring Boot 框架,可以直接使用 Spring Framework 自带的定时任务,使用上面两种定时任务的实现方式,很难实现设定了具体时间的定时任务,比如当我们需要每周五来执行某项任务时,但如果使用 Spring Task 就可轻松的实现此需求。
以 Spring Boot 为例,实现定时任务只需两步:
开启定时任务;
添加定时任务。
开启定时任务只需要在 Spring Boot 的启动类上声明 @EnableScheduling
即可,实现代码如下:
@SpringBootApplication
@EnableScheduling //开启定时任务
public class ClubApplication {
public static void main(String[] args) {
SpringApplication.run(ClubApplication.class, args);
}
}
定时任务的添加只需要使用 @Scheduled
注解标注即可,如果有多个定时任务可以创建多个 @Scheduled
注解标注的方法,示例代码如下:
/**
* 定时任务
* 重置每周,每月的在线时间
*/
@Component
public class ResetTime {
@Autowired
private UserMapper userMapper;
User user = new User();
/**
* 每月最后 1 日 23:30 触发
*/
@Scheduled(cron = "* 30 23 L * ? ")
public void resetMonthTime(){
user.setMonthTime(0);
this.userMapper.update(user,null);
}
}
Cron 表达式
在线生成cron:Cron表达式生成器 - Toolzl工具