SchedulerHelper 定时任务帮助类,ScheduledThreadPoolExecutor实现

1、前言

ScheduledThreadPoolExecutor是一个使用线程池执行定时任务的类,相较于Java中提供的另一个执行定时任务的类Timer,其主要有如下两个优点:

  • 使用多线程执行任务,不用担心任务执行时间过长而导致任务相互阻塞的情况,Timer是单线程执行的,因而会出现这个问题;
  • 不用担心任务执行过程中,如果线程失活,其会新建线程执行任务,Timer类的单线程挂掉之后是不会重新创建线程执行后续任务的。

除去上述两个优点外,ScheduledThreadPoolExecutor还提供了非常灵活的API,用于执行任务。其任务的执行策略主要分为两大类:①在一定延迟之后只执行一次某个任务;②在一定延迟之后周期性的执行某个任务。

  public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
  public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
  public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
  public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

2、代码

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

public class SchedulerHelper {
    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);

    public static void main(String[] args) {
        SchedulerHelper helper1 = SchedulerHelper.getSelf();
        helper1.scheduleAtFixedRate(() -> {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            System.out.println(sdf.format(new java.util.Date()));
        }, 1000);
    }

    public static SchedulerHelper getSelf() {
        return new SchedulerHelper();
    }

    /**
     * 在一定延迟之后周期性的执行某个任务
     * 执行任务的间隔是固定的
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long period) {
        return executor.scheduleAtFixedRate(command, 0, period, TimeUnit.MILLISECONDS);
    }

    /**
     * 在一定延迟之后周期性的执行某个任务
     * 执行任务的间隔是固定的
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period) {
        return executor.scheduleAtFixedRate(command, initialDelay, period, TimeUnit.MILLISECONDS);
    }

    /**
     * 在一定延迟之后周期性的执行某个任务
     * 执行时间间隔是不固定的
     * 其会在周期任务的上一个任务执行完成之后才开始计时
     * 并在指定时间间隔之后才开始执行任务
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay) {
        return executor.scheduleAtFixedRate(command, initialDelay, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 在一定延迟之后只执行一次某个任务
     */
    public ScheduledFuture<?> schedule(Runnable command, long delay) {
        return executor.schedule(command, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 在一定延迟之后只执行一次某个任务
     */
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay) {
        return executor.schedule(callable, delay, TimeUnit.MILLISECONDS);
    }
}

3、参考

ScheduledThreadPoolExecutor详解
Java多线程和并发知识点详细总结(RedSpider社区)

posted @ 2022-05-22 16:37  一只桔子2233  阅读(27)  评论(0编辑  收藏  举报