package com.kym.service.jobs;

import jakarta.validation.constraints.NotNull;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author skyline
 * @description 延迟执行
 * @date 2023-10-08 21:43
 */
public class DelayedItem<T> implements Delayed {
    /**
     * 业务对象
     */
    public final T data;

    /**
     * 定时时间
     */
    public LocalDateTime delayTime = LocalDateTime.MIN;

    public DelayedItem(T data, LocalDateTime delayTime) {
        this.data = data;
        this.delayTime = delayTime;
    }


    @Override
    public long getDelay(@NotNull TimeUnit unit) {
        return unit.convert(delayTime.toInstant(ZoneOffset.ofHours(+8)).toEpochMilli() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(@NotNull Delayed o) {
        return (int) (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
