package com.yeejoin.amos.supervision.task;

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.supervision.business.service.intfc.IPlanTaskService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author DELL
 */
@Component
@EnableScheduling
public class PlanTaskJob {

    @Autowired(required = false)
    org.redisson.api.RedissonClient redisson;

    @Value("${spring.redis.mode}")
    private String cluster;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IPlanTaskService planTaskService;

    /**
     * 定时查询任务状态
     */
    @Scheduled(cron = "${jobs.cron}")
    public void scheduleJob() {
        System.out.println("开始执行定时任务============");
       if("cluster".equals(cluster)){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time=format.format(new Date());
        String jobName = "supervision-1" +time;


        RLock lock = redisson.getLock(jobName);
        try {
            //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
            lock.tryLock(10, 20, TimeUnit.SECONDS);
            System.out.println("获取锁成功============");
            //为了防止重复
            if (!redisUtils.hasKey(jobName + "_redisson_key")) {
                redisUtils.set(jobName + "_redisson_key", "1");//
                planTaskService.taskExecution(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //释放锁

        }
       }else{
           planTaskService.taskExecution(null);
       }
    }
}
