JAVA - Service层使用定时器 - 开始任务 - 结束任务

169 阅读1分钟
/**
 * 定时任务线程
 */
private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

/**
 * 定时任务
 */
private static volatile ScheduledFuture<?> scheduledFuture;

/**
 * 定时器初始化时间
 */
private static final long INITIAL_DELAY = 0L;

/**
 * 定时器间隔时间
 */
private static final long PERIOD = 1L;

@Override
public ResponseDto start(RequestDto requestDto) {
    String path = gradingUrlHuawei + "/mock/start";
    // 调用外部接口,开始判级,准备拍照
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(path, requestDto, String.class);
    String body = responseEntity.getBody();
    // 启动定时器,轮训照片库,调用判级服务
    this.schedulerStart(() -> gradingResultService.gradingImage());

    return new ResponseDto();
}

private void schedulerStart(Runnable command) {
    if (scheduledFuture == null) {
        synchronized (this) {
            if (scheduledFuture == null) {
                System.out.println("判级开始");
                scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(command, INITIAL_DELAY, PERIOD, TimeUnit.SECONDS);
            }
        }
    }
}

private void schedulerStop() {
    if (scheduledFuture != null) {
        synchronized (this) {
            if (scheduledFuture != null) {
                System.out.println("判级结束");
                scheduledFuture.cancel(false);
                scheduledFuture = null;
            }
        }
    }
}

@Override
public ResponseDto stop(RequestDto requestDto) {
    String path = gradingUrlHuawei + "/mock/stop";
    // 停止任务、拍照
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(path, requestDto, String.class);
    String body = responseEntity.getBody();
    // 关闭定时器
    this.schedulerStop();

    return null;
}