配置文件
package com.sf.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author yachun
* @date 2019/7/5
*/
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setTaskScheduler(taskScheduler());
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
// 配置线程池大小,根据任务数量定制
taskScheduler.setPoolSize(10);
// 线程名称前缀
taskScheduler.setThreadNamePrefix("spring-task-scheduler-thread-");
// 线程池关闭前最大等待时间,确保最后一定关闭
taskScheduler.setAwaitTerminationSeconds(60);
// 线程池关闭时等待所有任务完成
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
// 任务丢弃策略
taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
return taskScheduler;
}
}
执行任务代码
package com.sf.controller;
import com.sf.dao.mapper.BusinessCooperationMapper;
import com.sf.dao.model.BusinessCooperationDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author yachun
* @date 2019/7/5
*/
@Slf4j
@Component
public class BussinessTask {
@Autowired
private RedisTemplate redisTemplate;
@Resource
private BusinessCooperationMapper businessCooperationMapper;
private static final String PT = "bussinessTask";
/**
* 合作到期供应商合作修改审核状态
* TODO 需要改为@Scheduled(cron = "0 0 0 ? ? ?")
*/
@Scheduled(cron = "0 0 0 ? ? ?")
public void pvTask() {
log.info("----------------------------进入到我的BussinessTask定时器了-----------------");
String bussinessTask = (String) redisTemplate.opsForValue().get("bussinessTask");
if (!StringUtils.equals(PT, bussinessTask)) {
// 需要把时间改为1分钟
redisTemplate.opsForValue().set("bussinessTask", "1", 1, TimeUnit.MINUTES);
List<Long> ids = businessCooperationMapper.listBuessIds();
//执行修改供应商的审核状态为-- 2.合作到期
if (ids != null && ids.size() > 0) {
ids.stream().forEach(x -> {
BusinessCooperationDO temp = new BusinessCooperationDO();
temp.setId(x);
temp.setAuditStatus(2);
businessCooperationMapper.updateByPrimaryKeySelective(temp);
log.info("----------------------------执行到修改供应商过期的审核状态的地方了-----------------");
});
}
}
}
}