@Component
@Slf4j
public class dataTask implements InitializingBean {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Autowired
private dataTaskService dataTaskService;//自己项目的service
private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
/**
* 项目启动时运行
*/
@Override
public void afterPropertiesSet() throws Exception {
List<DataTask> dataTasks= dataTaskService.getDataTask();
for(DataTasktask:dataTasks){
startRobotTask(task);
}
}
/**
* 开启定时任务
* @param task
*/
public void startRobotTask(DataTask task) {
ScheduledFuture future = threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
dataTaskService.collectData(task);//要执行的方法体
}
},new Trigger(){
@Override
public Date nextExecutionTime(TriggerContext triggerContext){
DataTask dataTask= dataTaskService.getById(task.getId());
String cron = "0 */5 * * * ?";
if (dataTask!= null && StringUtils.isNotEmpty(collect.getCron())) {
cron = dataTask.getCron();
}
CronTrigger trigger = new CronTrigger(cron);
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
});
taskFutures.put(task.getId(),future);
}
/**
* 停止定时任务
*/
public void stopTask(String taskId) {
ScheduledFuture<?> future = taskFutures.get(taskId);
if (future != null) {
//不会马上停止任务,会等任务执行完
future.cancel(true);
}
taskFutures.remove(taskId);
}
}
同一个表的各条数据分别执行各自定时任务,cron表达式随时可变,定时任务开始、停止。