package com.unit.util;


import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtil {
    private final static ScheduledThreadPoolExecutor POOL;
    static {
        POOL = new ScheduledThreadPoolExecutor(2);
        POOL.setKeepAliveTime(60, TimeUnit.SECONDS);
        POOL.setRejectedExecutionHandler((runnable, threadPoolExecutor) -> Log.d("ThreadPool","execute rejected"));
    }
    public static void execute(Runnable command) {
        POOL.execute(command);
    }
    public static ScheduledFuture<?> execute(Runnable command, long delay, TimeUnit unit) {
        return POOL.schedule(command, delay, unit);
    }

    public static void remove(Runnable runnable) {
        POOL.remove(runnable);
    }

    public static void uiRun(Runnable runnable){
        uiRun(runnable, 0);
    }
    public static void uiRun(Runnable runnable, long delayMillis){
        if (runnable == null) {
            return;
        }
        if (Looper.myLooper()==Looper.getMainLooper() && delayMillis<=0){
            runnable.run();
            return;
        }
        new Handler(Looper.getMainLooper()).postDelayed(runnable, delayMillis);
    }
}
