使用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 ( "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 (); }
在接口传入的dto中传入释放时间PushTime
long delay = pushTime . getTime () - System . currentTimeMillis (); # The release time minus the current time is the delay time delay
调用 ScheduledExecutorService
public ScheduledFuture <?> schedule ( Runnable command , long delay , TimeUnit unit );
api方法
可实现定时发布视频功能