package com.uas.core.support;


import com.uas.task.ScheduleTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
@Configuration
@EnableScheduling
@Component
public class SpringDynamicCronTask implements SchedulingConfigurer {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());


	@Autowired
	private Environment env;

	@Autowired
	private ScheduleTask scheduleTask;

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		String activeProFiles = env.getActiveProfiles()[0];
		if(!"dev".equals(activeProFiles)) {
			logger.info(String.format("运行环境：%s;注册TASK:%s",activeProFiles,env.getProperty("Task.Method")));
			taskRegistrar.addCronTask(() -> {
				//业务逻辑
				try {
					Method method = scheduleTask.getClass().getMethod(env.getProperty("Task.Method"));
					method.invoke(scheduleTask);
				}catch (Exception e){
					e.printStackTrace();
				}
			}, env.getProperty("Task.Cron"));
		}
	}
}
