定制任务服务 ScheduledTaskService
自定义的定时任务服务 ScheduledTaskService
package com.joyupx.service.impl.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.Task;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
/**
* 定制任务服务
*
* @author hapday
* @since 1.0
*/
@Slf4j
@Service
public class ScheduledTaskService {
// 线程池任务调度器
private final ThreadPoolTaskScheduler threadPoolTaskScheduler;
// 声明【定制任务未来】引用
private ScheduledFuture<?> scheduledFuture;
// 定时注解豆发送处理器
@Autowired
private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor;
public ScheduledTaskService(ThreadPoolTaskScheduler taskScheduler) {
this.threadPoolTaskScheduler = taskScheduler;
}
// @Scheduled ( fixedRate = 1000) // 如果用注解,则 startTask 方法和 stopTask 方法将失效,因为它的优先级高于手动启动的优先级
public void scheduleTask() {
// 你的任务逻辑
log.info("\n\n\t\t\t》》》运行定时任务《《《\n\n");
}
/**
* 启动任务
*/
public void startTask() {
// 创建【任务的触发器】对象
Trigger taskTrigger = new CronTrigger("*/1 * * * * *");
// 周期性执行,比如这里设置为了 1 秒中执行一次
// trigger = new PeriodicTrigger(1000);
// 立即启动
// future = taskScheduler.schedule(this::scheduleTask, new Date());
scheduledFuture = threadPoolTaskScheduler.schedule(this::scheduleTask, taskTrigger);
}
/**
* 停止任务
*/
public void stopTask() {
if (null != scheduledFuture) {
// 通过未来对象取消任务的执行。
scheduledFuture.cancel(false);
}
}
/**
* 查询运行中的任务
*
* @return 任务集
*/
public Set<String> runningTaskList() {
/*
* 无法获取到非注解启动的定时任务
* 只能获取到通过注解启动的任务
*/
Set<ScheduledTask> scheduledTasks = scheduledAnnotationBeanPostProcessor.getScheduledTasks();
Set<String> runningTaskSet = new HashSet<>(scheduledTasks.size());
for (ScheduledTask scheduledTask : scheduledTasks) {
// 获取任务
Task task = scheduledTask.getTask();
// 获取可运行的任务
Runnable runnableTemp = task.getRunnable();
// 声明【定时方法可运行】引用
ScheduledMethodRunnable scheduledMethodRunnable = null;
/*
* 排除非定时方法的可运行任务
*/
if (runnableTemp instanceof ScheduledMethodRunnable)
scheduledMethodRunnable = (ScheduledMethodRunnable) runnableTemp;
/*
* 排除空对象
*/
if (null == scheduledMethodRunnable) {
continue;
}
Object taskFullyQualifiedName = scheduledMethodRunnable.getTarget();
log.debug("\n\n######### Running task:{}", taskFullyQualifiedName);
// 将task所关联的对象放到Set中(就是带@Scheduled方法的类)
runningTaskSet.add(taskFullyQualifiedName.toString());
}
return runningTaskSet;
}
}