使用ScheduledExecutorService实现延时任务——延时发布视频

使用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方法

就可以实现在定时的时间发布视频的功能

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值