一、常用的定时任务管理XXL-JOB,但是如果快速使用定时任务使用
ApplicationRunner也很快,不要引入第三方包
示例代码:
java
import cn.ctg.bfws.client.CtgConfigureClient;
import cn.ctg.bfws.vo.PmApproveHourVo;
import cn.ctg.common.response.ResponseData;
import cn.ctg.configure.dto.SysProjectDto;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 线程服务类
*
* @Description:
*/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ToolServiceThread implements ApplicationRunner {
@Resource
private CtgConfigureClient ctgConfigureClient;
@Resource
private PmApproveService pmApproveService;
@Value("${bill.projectGs.billTempId:}")
private String billTempId;
@Value("${bill.projectGs.comTempCode:}")
private String comTempCode;
@Value("${bill.projectGs.categoryId:}")
private String categoryId;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("开启线程.....,");
}
/**
* 每5分钟后执行
*/
@Scheduled(cron = "0 */5 * * * ?")
public void executeEvery30Seconds () throws Exception {
//自动拉取成员单,更新项目经理工时单
log.info("更新项目经理工时单...");
ResponseData<List<SysProjectDto>> res = ctgConfigureClient.selectList();
YearMonth yearMonthObj = YearMonth.now();
String yearMonth = yearMonthObj.format(DateTimeFormatter.ofPattern("yyyyMM"));
if(res.isSuccess()){
List<SysProjectDto> list = res.getData();
for (SysProjectDto sysProjectDto : list) {
PmApproveHourVo vo = new PmApproveHourVo();
vo.setMonth(yearMonth);
vo.setProjectCode(sysProjectDto.getCode());
String userId =sysProjectDto.getManagers();
if(sysProjectDto.getManagers().contains("^")) {
userId = sysProjectDto.getManagers().split("^")[0];
}
pmApproveService.waitApproveList(vo,userId);
log.info("更新项目经理工时单...:{}", JSON.toJSONString(sysProjectDto));
}
}
}
/**
* 每月5号生成项目经理公式模版示例
*/
@Scheduled(cron = "0 0 0 5 * ?")
public void createPmGsBill () throws Exception {
//自动拉取成员单,更新项目经理工时单
log.info("每月5号生成项目经理工时模版...");
ResponseData<List<SysProjectDto>> res = ctgConfigureClient.selectList();
YearMonth yearMonthObj = YearMonth.now();
String yearMonth = yearMonthObj.format(DateTimeFormatter.ofPattern("yyyyMM"));
//pmApproveService.createProjectBill(billTempId,comTempCode,categoryId);
}
}
注意的是需要在启动类上加上注解
@EnableScheduling 要不然定时任务是无效的
示例:

