Using ScheduledExecutorService can implement timed tasks (such as the function of timed release)
First define local variables in the class
ScheduledExecutorService service = Executors.newScheduledThreadPool(50);
Executors.newScheduledThreadPool(50); Factory pattern is used here.
factory pattern
It is mainly to provide a transition interface for creating objects, so as to shield and isolate the specific process of creating objects and achieve the purpose of improving flexibility.
@PostMapping("/ops/scheduled/publish") public ResponseResult scheduledPublish(@RequestBody ScheduleVideoDto dto) { List<Integer> vids = dto.getVids(); if (vids.isEmpty()){ return ResponseResult.of().withErrorMessage("Failed to publish video, please select a video to publish"); } Date pushTime = dto.getPushTime(); if (pushTime==null){ return ResponseResult.of().withErrorMessage("Failed to publish the video, please re-select the publishing time"); } 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("Failed to publish video, the selected videos are all published"); } long delay = pushTime.getTime() - System.currentTimeMillis(); vids.forEach(vid->{ videoService.updatePushTime(vid,pushTime); service.schedule(() -> videoService.publish(vid), delay, TimeUnit.MILLISECONDS); }); return ResponseResult.of(); }
Pass in the release time PushTime in the dto passed in the interface
long delay = pushTime.getTime() - System.currentTimeMillis(); #The release time minus the current time is the delay time delay
Calling ScheduledExecutorService
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
api method
It can realize the function of publishing video at a fixed time
Top comments (0)