使用ScheduledThreadPoolExecutor对象实现文章的定时发布

1、首先定义 ScheduledThreadPoolExecutor 对象 而ScheduledThreadPoolExecutor 对象间接继承了Executor(执行器)

//创建线程
public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);

2、静态方法

//定义方法根据传入的时间 对文章进行定时发布
public static void execution(ScheduledThreadPoolExecutor executor, Runnable runnable, String startTime) {
        try {
        //对传入的字符串时间进行格式化
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
            //获取时间戳 
            long startLong = startDate.getTime() - new Date().getTime();
            //调用执行器schedule 方法
            executor.schedule(runnable, startLong, TimeUnit.MILLISECONDS);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    //源码中的 schedule方法
    /**
     * @throws RejectedExecutionException {@inheritDoc}
     * @throws NullPointerException       {@inheritDoc}
     */
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
            //decorateTask 
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }

3.方法调用

//RunnableXXX 创建子类实现
execution(executor, new RunnableXXX(唯一标识),需要定时发布的时间);

4.创建的RunnableXXX 类

public class RunnableXXX implements Runnable {
    String 标识;

    public RunnableXXX(主键标识) {
        this.标识 = 主键标识;
    }
    //重新Runnable 的run方法
    @Override
    public void run() {
        //写需要定时发布的业务逻辑
    }

tips

//时间格式问题处理
问题:
	比如将“2022-07-20T09:32:04.000+0800”转化为“2022-07-20 09:32:04”的时间格式,转化方式为:
解决
  SimpleDateFormat startDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
  SimpleDateFormat startDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String time1 = startDateFormat1.format(startDateFormat.parse(contentdto.getTimingTime()));
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值