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()));