使用ScheduledExecutorService可以實現定時任務(例如定時發佈的功能)
先在類中定義局部變量
ScheduledExecutorService service = Executors.newScheduledThreadPool(50);
Executors.newScheduledThreadPool(50); 此處使用了工廠模式。
工廠模式
主要是爲創建對象提供過渡接口,以便將創建對象的具體過程屏蔽隔離起來,達到提高靈活性的目的。
@PostMapping("/ops/scheduled/publish")
public ResponseResult scheduledPublish(@RequestBody ScheduleVideoDto dto) {
List<Integer> vids = dto.getVids();
if (vids.isEmpty()){
return ResponseResult.of().withErrorMessage("發佈視頻失敗,請選擇視頻進行發佈");
}
Date pushTime = dto.getPushTime();
if (pushTime==null){
return ResponseResult.of().withErrorMessage("發佈視頻失敗,請重新選擇發佈時間");
}
for (int i = 0; i< vids.size();i++){
int status = videoService.getStatusById(vids.get(i));
if (status==1) vids.remove(vids.get(i));
}
if (vids.isEmpty()){
return ResponseResult.of().withErrorMessage("發佈視頻失敗,所選視頻均爲已發佈");
}
long delay = pushTime.getTime() - System.currentTimeMillis();
vids.forEach(vid->{
videoService.updatePushTime(vid,pushTime);
service.schedule(() -> videoService.publish(vid), delay, TimeUnit.MILLISECONDS);
});
return ResponseResult.of();
}
在接口傳入的dto中傳入發佈時間PushTime
long delay = pushTime.getTime() - System.currentTimeMillis();
發佈時間減去當前時間就是延時時間delay
調用ScheduledExecutorService 的
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
api方法
就可以實現在定時的時間發佈視頻的功能