项目启动类上添加
@EnableScheduling // 2.开启定时任务
定时任务的类上添加
package com.sixnoble.modules.evaluation.comment.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration //1.主要用于标记配置类,兼备Component的效果。 注入依赖
public class TimedTask {
@Autowired
private BzCommentService bzCommentService;
// @Scheduled(cron = "0 1 0 * * ?")
@Scheduled(cron = "30 * * * * ?")
public void updateState() {
bzCommentService.timedTask();
}
}
例:
/**
* 用户未评价按时自动好评
*/
public void timedTask() {
BzUserConsultForm bzUserConsultForm = new BzUserConsultForm();
bzUserConsultForm.setConsultState(7); //待评价
List<BzUserConsultForm> list = bzUserConsultFormServiceClient.findList(bzUserConsultForm);
for (BzUserConsultForm bzUserConsultForm1 : list){
Date date = bzUserConsultForm1.getUpdateTime();
long time = date.getTime();
// long fakeTime = 60*60*24*1000*7;
String pingjia_days = DictUtils.getDictValue("bz_payment_config","pingjia_days","");
long pingjia_days1 = Long.parseLong(pingjia_days);
long end = pingjia_days1*60*1000;
long date1 = new Date().getTime();
long sumTime = (time + end );
if(date1 > sumTime){
BzComment bzComment = new BzComment();
//查询用户
String employeeId = bzUserConsultForm1.getEmployeeId();
BzUserEmployee byId = bzUserEmployeeServiceClient.getById(employeeId);
String employeeName = byId.getEmployeeName();
bzComment.setUserId(employeeId);
bzComment.setUserName(employeeName);
//查询咨询师
String counselorId = bzUserConsultForm1.getCounselorId();
BzCounselor byId1 = bzCounselorServiceClient.getById(counselorId);
String name = byId1.getName();
String title = byId1.getTitle();
bzComment.setCounselorId(counselorId);
bzComment.setCounselor(name);
bzComment.setTitle(title);
bzComment.setCommentTime(new Date());
bzComment.setCommentScore("5");
bzComment.setCommentScoreAttitude("5");
bzComment.setCommentScoreKnowledge("5");
super.save(bzComment);
log.info("自动好评-------------用户id-----"+employeeId);
//给咨询记录发送订单编号
ConsultFormDto consultFormDto = new ConsultFormDto();
consultFormDto.setOrderSn(bzUserConsultForm1.getOrderSn());
amqpTemplate.convertAndSend("UpdateConsultCompletedState","",consultFormDto);
}
}
}
将定时时间配置在yml中
配置文件application.yml示例:
schedules:
3600000
//or
schedules:
0/15 * * * * ?
代码示例:
@Scheduled(fixedDelayString="${schedules}") //schedules: 3600000
//or 加在需要定时的方法上
@Scheduled(cron="${schedules}")