package cc.smtweb.framework.core.systask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Akmm at 2018/11/27 23:40
 * 后台系统任务工厂，不允许用户干预的任务放在这里
 */
public class SysServiceFactory {
    //允许的最大线程个数
    private static final int max_thread_size = 16;
    private static SysServiceFactory instance = null;

    static {
        instance = new SysServiceFactory();
    }

    public static SysServiceFactory getInstance() {
        return instance;
    }


    private ScheduledExecutorService schedule;
    //待执行的任务
    private List<BaseSysService> listService = new ArrayList<>();

    public SysServiceFactory() {

    }

    //注册任务
    public void reg(BaseSysService service) {
        listService.add(service);
    }


    //启动任务
    public void start() {
        if (schedule != null) {
            stop();
        }
        int size = listService.size();
        if (size > max_thread_size) size = max_thread_size;
        schedule = Executors.newScheduledThreadPool(size);
        for (BaseSysService s : listService) {
            schedule.scheduleWithFixedDelay(s, 60L, (long) s.getInterval(), TimeUnit.SECONDS);
        }
    }

    //停止任务
    public void stop() {
        if (schedule != null) schedule.shutdown();
    }
}
