定时器

这里的定时器就是一个实现定时调用的函数,接口就两个:启动和停止。

public interface TaskJobScheduler {

    /**
     * 启动定时器
     */
    void start();

    /**
     * 停止定时器
     */
    void stop();
}

定时器的启动之后就会定时调用触发器,具体代码如下:

@Slf4j
public class DefaultTaskJobScheduler implements TaskJobScheduler {

    private Thread scheduleThread;
    private final ScheduleTaskTrigger scheduleTaskTrigger;
    private volatile boolean scheduleThreadToStop = false;

    public DefaultTaskJobScheduler(ScheduleTaskTrigger scheduleTaskTrigger) {
        this.scheduleTaskTrigger = scheduleTaskTrigger;
    }


    @Override
    public void start() {
        scheduleThread = new Thread(()->{
            while (!scheduleThreadToStop) {
                scheduleTaskTrigger.trigger();
                threadSleep();
            }
            log.info("scheduleThread stop");
        });
        scheduleThread.setDaemon(true);
        scheduleThread.setName("scheduleThread");
        scheduleThread.start();
        log.info("scheduleThread start success");
    }

    @Override
    public void stop() {
        scheduleThreadToStop = true;
        stopThread(scheduleThread);
        log.info("scheduleThread stop success");
    }

    // 每秒调度一次
    protected void threadSleep(){
        try {
            TimeUnit.MILLISECONDS.sleep(1000 - System.currentTimeMillis() % 1000);
        } catch (InterruptedException e) {
            if (!scheduleThreadToStop) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 停止线程
     * @param thread 要停止的线程
     */
    private void stopThread(Thread thread){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }

        if (thread.getState() == Thread.State.TERMINATED){
            return;
        }

        // interrupt and wait
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }
}