package com.pcloud.book.group.handler;

import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.common.utils.DateUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Random;

import lombok.extern.slf4j.Slf4j;

/**
 * 项目启动制行的任务
 *
 * @author Gui_q
 * @since 2020年2月3日 12点14分
 */
@Component
@Slf4j
public class PushBookGroupUpdateRunner implements ApplicationRunner {

    @Autowired
    private BookGroupBiz bookGroupBiz;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("[启动时开始推送1v1更新]");
        new Thread(() -> {
            while (true) {
                //随机睡10到15s
                Long sleepMillis = Double.valueOf(new Random().nextInt(10) + 5).longValue() * 1000;
                try {
                    //判断是否是早八点到晚八点之间
                    Boolean isInTime = DateUtils.isInBetweenTimes("08:00:00", "20:00:00");
                    if (isInTime) {
                        bookGroupBiz.pushBookGroupUpdate();
                    }
                    Thread.sleep(sleepMillis);
                } catch (Throwable e) {
                    log.error("启动时开始推送1v1更新异常" + e.getMessage(), e);
                    try {
                        Thread.sleep(sleepMillis);
                    } catch (InterruptedException ex) {
                        log.error("启动时开始推送1v1更新休眠异常" + e.getMessage(), e);

                    }
                }
            }
        }).start();
    }
}
