package com.elab.core.async.consumer;

import com.elab.core.async.SchedulingTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 调度消费者
 *
 * @author ： liukx
 * @time ： 2020/8/6 - 13:32
 */
public class SchedulingConsumer implements Runnable {

    private Logger logger = LoggerFactory.getLogger(SchedulingConsumer.class);
    /**
     * 调度任务
     */
    private List<SchedulingTaskExecutor> taskExecutors;


    /**
     * 间隔时间/秒
     */
    private int intervalTime;

    public SchedulingConsumer(List<SchedulingTaskExecutor> taskExecutors, int intervalTime) {
        this.taskExecutors = taskExecutors;
        this.intervalTime = intervalTime * 1000;
    }

    @Override
    public void run() {
        while (true) {
            try {
                taskExecutors.forEach((taskExecutor) -> {
                    CompletableFuture.runAsync(() -> {
                        taskExecutor.process();
                    });
                });
            } catch (Exception e) {
                logger.error("定时调度异常", e);
            } finally {
                try {
                    Thread.sleep(intervalTime);
                } catch (InterruptedException e) {
                    logger.error("中断异常", e);
                }
            }
        }
    }
}
