今天要做一个定时调度,更新一下一些数据的状态
上代码,先创建一个配置类
@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
@Autowired
DFNDTimeCronDao timeCronDao;
@Autowired
ExecuteScheduleService executeScheduleService;
/**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//2.1 从数据库获取执行周期
List<DFNDTimeCron> cronInfos = timeCronDao.TimeCronList();
//2.2 合法性校验.
for (DFNDTimeCron cronInfo : cronInfos) {
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> {
System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime());
},
//2.设置执行周期(Trigger)
triggerContext -> {
if (!StringUtils.isEmpty(cronInfo.getCron())) {
try {
executeScheduleService.execClassImpl(cronInfo.getType());
} catch (ParseException e) {
e.printStackTrace();
}
}
//2.3 返回执行周期(Date)
return new CronTrigger(cronInfo.getCron()).nextExecutionTime(triggerContext);
}
);
}
}
}
这下需要创建一张表
-- Create table
create table DFND_TIME_CRON
(
id NUMBER, 主键
cron VARCHAR2(200), 定时
remark VARCHAR2(200), 描述
createby VARCHAR2(200), 创建人
create_date DATE, 创建时间
type VARCHAR2(200), 类型
class VARCHAR2(200) java类
)
pojo类
记得映射哈
@Data
@Table(value = "DFND_TIME_CRON")
public class DFNDTimeCron extends MpaasBasePojo {
private String createby;
@JsonSerialize(using = MpaasDateSerializer.class)
@JsonDeserialize(using = MpaasDateDeserializer.class)
@Column(value = "CREATE_DATE")
private Date createDate;
private Long id;
private String cron;
private String remark;
private String type;
}
执行方法:
@Service
public class ExecuteScheduleService {
@Autowired
ScheduleNoticeTask scheduleNoticeTask;
public boolean execClassImpl(String type) throws ParseException {
//出门证销项邮件提醒
if(!"".equals(type)&&"ExitSales".equals(type)){
scheduleNoticeTask.configureTasks();
return true;
}else if(!"".equals(type)&&"UpdateSalesStatus".equals(type)){
scheduleNoticeTask.updateSalesStatus();
}
return false;
}
}