使用@Scheduled创建定时任务
https://blog.csdn.net/weixin_42033269/article/details/101477871
下面用之前的为基础进行介绍
https://blog.csdn.net/Oceansssss/article/details/122668633
- 在MyUserService中添加接口
public void openSchedule();//开启定时任务
- 在MyUserServiceImpl中添加如下
@Service
@Data //添加@Data注解
public class MyUserServiceImpl implements MyUserService{
@Autowired
private MyUserServiceImpl myUserServiceImpl; //添加MyUserServiceImpl的实例
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void testTasks() {
if(myUserServiceImpl.getFlag()==1){
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}
}
}
- MyUserController中添加方法
@RequestMapping("/open")
public String openSchedule(){
myUserService.openSchedule();
return "open schedule successfully";
}
- 启动类中添加注解@EnableScheduling
@SpringBootApplication()
@EnableScheduling //添加
@MapperScan(basePackages={"com.example.demo.repository"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 运行结果
启动
开启定时任务
源码下载
https://download.csdn.net/download/Oceansssss/78172573