/**
 *
 */
package com.cnd3b.common;

import com.cnd3b.common.data.db.SQLiteJDBC;
import p2.p2server.ScheduleTaskService;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 *
 */
public class InitService extends ScheduleTaskService {
    public InitService() {

    }

    private static boolean isfirstrun = true;

    @Override
    public void cronAction() {
        if (isfirstrun) {
            System.err.println("启动自动任务");
            isfirstrun = false;
            ArrayList<HashMap<String, Object>> list = new SQLiteJDBC().getServices();
            if (!list.isEmpty()) {
                runService(list);
            }
        }
    }


    public void runService(ArrayList<HashMap<String, Object>> list) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(list.size());
        int starttime = 5;
        for (HashMap<String, Object> map : list) {
            try {
                String classname = map.get("classname").toString();
                String remarks = map.get("remarks").toString();
                long intervaltime = (long) map.get("intervaltime");

                boolean used = (boolean) map.get("used");
                new SQLiteJDBC().InsertLogMsg("服务加载", classname + "," + intervaltime + "," + used + ";" + remarks,
                        "info");
                System.err.println("服务加载："+classname + "," + intervaltime + "," + used + ";" + remarks);
                Class<?> clz = Class.forName("com.cnd3b.service." + classname);
                Constructor<?> cla = clz.getDeclaredConstructor();
                Object obj = cla.newInstance();
                service.scheduleWithFixedDelay((Runnable) obj, starttime, intervaltime, TimeUnit.SECONDS);
                starttime = starttime + 5;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
