package com.example.config;

import com.example.action.GlobalController;
import com.example.frame.base.Message;
import com.example.frame.base.MessageType;
import com.example.frame.utils.LogUtil;
import com.example.frame.utils.ProcessUtil;
import com.example.module.admin.ent.NginxCtrl;
import com.example.module.admin.ent.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

/**
 * Task配置，默认只在开发环境生效,根据实际情况是否需要Task选择开启
 * 开启方法:将@Profile("dev") 删除(所有环境生效) 或改为 @Profile("prod")(只对生产环境生效)
 */
@Configuration
@EnableScheduling
//@Profile("prod")
public class TaskConfig implements SchedulingConfigurer {

    @Autowired
    private GlobalController globalController;
    @Autowired
    private NginxCtrl nginxCtrl;

    @Scheduled(cron = "0/3 * * * * ? ")
    public void task() {
        Message message = new Message();
        message.setType(MessageType.NGINX_STATE);
        State state = new State();
        state.setRun(nginxCtrl.isRunning());
        message.setObject(state);
        globalController.pushAll(message);
    }

    /**
     * Spring的 Schedule 默认是单线程执行
     * 若要多线程并行运行任务 需实现SchedulingConfigurer并重写configureTasks方法
     *
     * @param scheduledTaskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(3));
    }
}
