package com.railway.framework.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @Description: 基于接口SchedulingConfigurer的动态定时任务
 * @Author:
 */
@Configuration
@EnableScheduling
public abstract class ConfigurerSchedulingTask implements SchedulingConfigurer {

  //定时任务周期表达式
  private String cron;
  /**
   * @Description:  重写配置定时任务的方法
   * @param: scheduledTaskRegistrar
   * @return: void
   * @Author:
   */
  @Override
  public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
    scheduledTaskRegistrar.setScheduler(taskScheduler());
    scheduledTaskRegistrar.addTriggerTask(
            //执行定时任务
            () ->
            {
              taskService();
            },
            //设置触发器
            triggerContext -> {

              cron = getCron();//获取定时任务周期表达式

              CronTrigger trigger = new CronTrigger(cron);

              return trigger.nextExecutionTime(triggerContext);
            }
    );

  }

  public Executor taskScheduler() {
    //设置线程名称
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
    //创建线程池
    return Executors.newScheduledThreadPool(5, namedThreadFactory);
  }

  /**
   * @Description: 执行定时任务
   * @param:
   * @return: void
   * @Author:
   */
  public abstract void taskService();

  /**
   * @Description: 获取定时任务周期表达式
   * @param:
   * @return: java.lang.String
   * @Author:
   */
  public abstract String getCron();

}
