首先在Applicantion启动类上添加主键
@EnableScheduling//开启定时任务
@EnableAsync//开启异步任务
public class MsgserviceApplication implements ApplicationListener<ContextRefreshedEvent> {
public static void main(String[] args) {
SpringApplication.run(MsgserviceApplication.class, args);
}
//启动类继承ApplicationListener<ContextRefreshedEvent>类后就可以在程序启动时执行一次任务。
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//这里调用执行的任务
}
定时任务
@Component
public class SysstemSchedu {
@Scheduled(cron = "0 */60 * * * ?") //每60分钟执行一次任务
public void getAppToken() {
//里面执行业务
}
}
@Scheduled常用语法
每隔5秒执行一次: @Scheduled(cron = "*/5 * * * * ?")
每隔1分钟执行一次: @Scheduled(cron = "0 */1 * * * ?")
每天23点执行一次: @Scheduled(cron = "0 0 23 * * ?")
每天凌晨1点执行一次: @Scheduled(cron = "0 0 1 * * ?")
每月1号凌晨1点执行一次: @Scheduled(cron = "0 0 1 1 * ?")
每月最后一天23点执行一次: @Scheduled(cron = "0 0 23 L * ?")
每周星期天凌晨1点实行一次: @Scheduled(cron = "0 0 1 ? * L")
在26分、29分、33分执行一次: @Scheduled(cron = " 0 26,29,33 * * * ?")
每天的0点、13点、18点、21点都执行一次: @Scheduled(cron = " 0 0 0,13,18,21 * * ?")
异步任务
/**
* @author qingshi
* @date 2022/9/28 11:18
* info:异步处理类
*/
public interface SysncService {
/**
* 保存日志
*/
Future<String> saveSysLog(SysLog sysLog)throws Exception;
}
@Service
public class SysncServiceImpl extends BaseService implements SysncService{
@Async
@Override
public Future<String> saveSysLog(SysLog sysLog) throws Exception {
//执行业务方法
return new AsyncResult<>("保存日志");
}
}
//在其他service中调用sysncService的对应方法,即可异步执行
sysncService.saveSysLog(sysLog);//异步保存日志