TimedTask.java 2.18 KB
package com.bsth.task;

import com.bsth.common.SystemParamKeys;
import com.bsth.data.BasicData;
import com.bsth.entity.CarErrorStop;
import com.bsth.entity.SystemParam;
import com.bsth.util.HttpClientUtils;
import com.bsth.websocket.handler.SendUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class TimedTask {

    private final static Logger log = LoggerFactory.getLogger(TimedTask.class);

    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private SendUtils sendUtils;

    private Set<CarErrorStop> carErrorStopSet = new HashSet<>();

    @Scheduled(cron = "10 0 0 * * *")
    public void clear() {
        carErrorStopSet.clear();
    }

    @Scheduled(initialDelay = 10000, fixedDelay = 10000)
    public void carErrorStopTask() {
        SystemParam param = BasicData.getSystemParam().get(SystemParamKeys.API_URL_CARERRORSTOP);
        String url = null;
        if (param != null && param.getValue() != null) {
            url = param.getValue();
        }
        if (url == null) {
            log.error("carErrorStopTask url is null");
            return;
        }
        url = String.format(url, new DateTime().toString("yyyyMMdd"));
        try {
            StringBuilder sb = HttpClientUtils.get(url);
            if (sb != null) {
                List<CarErrorStop> carErrorStopList = mapper.readValue(sb.toString(), mapper.getTypeFactory().constructParametricType(List.class, CarErrorStop.class));
                for (CarErrorStop carErrorStop : carErrorStopList) {
                    //if (!carErrorStopSet.contains(carErrorStop)) {
                    //    carErrorStopSet.add(carErrorStop);
                        sendUtils.sendCarErrorStop(carErrorStop);
                    //}
                }
            }
        } catch (Exception e) {
            log.error("getAndSendCarErrorStop异常", e);
        }
    }
}