定时任务返回结果给方法

定时任务返回结果给方法

示例代码:

存在一些小问题,list会添加重复的数据,后面用到再优化一下

package com.sucsoft.video.service.develop;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 轮播画面定时器
 */
@Service
public class VsCarouselTimerService {

    private static ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
    private static final Logger logger = Logger.getLogger(VsCarouselTimerService.class);
    private static String url = "";

    private static Map map = new HashMap();
    private List<Map> list = new ArrayList<Map>();

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 每5分钟请求一次, 延迟1分钟开始执行
     * @param id
     */
    public void requestStream(String id) {
        // 防止重复创建线程
        if(Thread.currentThread().isAlive()) {
            this.pool.shutdown();
            pool = Executors.newScheduledThreadPool(5);
        }

        pool.scheduleAtFixedRate(() -> {
            try {
                map = restTemplate.getForObject(url, Map.class);
                list.add(map);
            } catch (Exception e) {
                logger.error(e);
            }
        }, 1, 300, TimeUnit.SECONDS);
    }

    /**
     * 转发流给前端
     * @return
     */
    public List<Map> forwardStream() {

        return list;
    }

}

posted @ 2018-11-29 15:46  柴田淳丿星  阅读(1735)  评论(0编辑  收藏  举报