import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(LuckSchedulingConfiguration.class)
@Documented
public @interface EnableLuckScheduling {
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TaskManagementConfigUtils;
import org.springframework.scheduling.support.PeriodicTrigger;
import java.util.concurrent.TimeUnit;
@Configuration
public class LuckSchedulingConfiguration {
/**
* 这里为什么要重写afterPropertiesSet方法,因为这个类注册为Bean,会自动调用afterPropertiesSet初始化方法
* 而在ScheduledAnnotationBeanPostProcessor中,容器刷新的使用会调用finishRegistration,内部会再次调用afterPropertiesSet
* 所以,我们屏蔽类创建时本身的回调,只执行容器刷新完成,手动调用这个回调初始化定时任务,否则可能出现发布两次任务
*/
@Bean
@Primary
public ScheduledTaskRegistrar luckRegistrar() {
ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar() {
private boolean running = false;
@Override
public void afterPropertiesSet() {
// 第一次执行
if (!running) {
running = true;
return;
}
super.afterPropertiesSet();
}
};
registrar.setTaskScheduler(taskScheduler());
// 如果不重写afterPropertiesSet,调用两次的情况下,下面添加的这个任务会执行两遍
// 为了保险起见,我们重写,当然,我们一般也不会这么做,所以,重写问题也不大,只是有可能出现意料不到的问题
registrar.addTriggerTask(() -> {
System.out.println("init task");
}, new PeriodicTrigger(1, TimeUnit.SECONDS));
return registrar;
}
/**
* 这个是正常的逻辑
*/
@Bean
public ScheduledTaskRegistrar registrar() {
ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
registrar.setTaskScheduler(taskScheduler());
return registrar;
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setErrorHandler(t -> System.out.println("发生异常," + t.getMessage() + ",正在处理中..."));
scheduler.setPoolSize(5);
scheduler.setThreadNamePrefix("luck-");
return scheduler;
}
@Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor(ScheduledTaskRegistrar registrar) {
ScheduledAnnotationBeanPostProcessor processor = new ScheduledAnnotationBeanPostProcessor(registrar);
// processor.setScheduler(taskScheduler());
return processor;
}
}
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@RequiredArgsConstructor
public class TaskManager {
private final ScheduledTaskRegistrar taskRegistrar;
private final Map<String, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>();
public void addTask(CronTask cronTask) {
// 执行任务
ScheduledTask task = taskRegistrar.scheduleCronTask(cronTask);
// 保存任务
scheduledTasks.put(cronTask.getExpression(), task);
}
public void cancel(String cron) {
ScheduledTask task = scheduledTasks.get(cron);
if (task != null) {
task.cancel();
}
}
public void cancelAll() {
if (CollUtil.isEmpty(scheduledTasks)) {
return;
}
scheduledTasks.values().forEach(ScheduledTask::cancel);
}
}
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.concurrent.TimeUnit;
// 这个就是为了导入ScheduledAnnotationBeanPostProcessor,而且没有传递任何参数,我们不方便随时随地的获取任务注册表
// 所以,我们自己来给定一个ScheduledAnnotationBeanPostProcessor,并且设置对应的注册表为我们随时随地可用
// @EnableScheduling
// 我们使用自己的开启定时任务类
@Import(TaskManager.class)
@EnableLuckScheduling
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:Administrator.properties")
public class Demo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Demo.class);
TaskManager manager = context.getBean(TaskManager.class);
System.out.println(manager);
String cron = "*/1 * * * * *";
manager.addTask(new CronTask(() -> {
System.out.println("Luck");
}, cron));
ThreadUtil.safeSleep(3000);
manager.cancel(cron);
}
// @Component
static class ScheduleBean implements SchedulingConfigurer {
@Scheduled(cron = "*/5 * * * * *")
public void scheduled() {
System.out.println("current time is " + DateUtil.now() + " thread is " + Thread.currentThread().getName() + " scheduled");
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 动态添加任务
taskRegistrar.addTriggerTask(() -> System.out.println(Thread.currentThread().getName() + " 正在执行 " + DateUtil.now()), new PeriodicTrigger(3, TimeUnit.SECONDS));
}
}
}
利用Spring的任务注册表动态操作定时任务
最新推荐文章于 2024-08-12 03:12:09 发布