SpringBoot搭建多线程定时任务
在一些系统上线之前,总需要后台定时执行一些事情。这个时候就需要定时任务来做这件事情。
多线程的目的是:使同一个定时任务模块的两个不同的定时任务业务不互相影响。在SpringBoot中集成了定时任务的简单配置
package com.resource.task;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
/**
* @program: travel-res-service
* @description: 定时任务
* @author: Andrea
* @create: 2019-11-15 14:54
**/
//@Component
@Configuration//标记启动类,兼备Component效果
@EnableScheduling//开启定时任务
@EnableAsync//多线程标记(两个定时任务不互相影响)
public class CornJob {
//或直接指定时间间隔,例如:5秒
//@Scheduled(fixedRate=5000)
//3.添加定时任务
@Async
@Scheduled(cron = "0 50 2 * * ?")//每天2:50分执行
public void cleanSegDatas() {
boolean b = //定时执行业务1的返回结果
if (b){
System.out.println("执行业务1完成");
}
System.err.println("执行执行业务1定时任务时间: " + LocalDateTime.now());
}
@Async
@Scheduled(cron = "0 0 3 * * ?")//每天3:00分执行
public void cleanTraRouteDatas() {
boolean b = //定时执行业务2的返回结果
if (b){
System.out.println("业务2完成");
}
System.err.println("执行业务2定时任务时间: " + LocalDateTime.now());
}
}