package com.iflytek.micro.brain.man.server.task;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.iflytek.database.mysql.dao.CypzMapper;
import com.iflytek.database.mysql.dao.MbNtpMapper;
import com.iflytek.database.mysql.domain.po.Cypz;
import com.iflytek.database.mysql.domain.po.MbNtp;
import common.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* @author songmo
* @Description: NTP 校时
* @date 2021/1/13 17:04
*/
@Configuration
@EnableScheduling
public class NtpTask implements SchedulingConfigurer {
private Logger logger = LoggerFactory.getLogger(NtpTask.class);
@Autowired
MbNtpMapper ntpMapper;
@Autowired
CypzMapper cypzMapper;
//每30分钟进行上传
private String cronPoints = "0 0/30 * * * ?";
private String getCronInfo() {
MbNtp mbNtp = ntpMapper.selectByPrimaryKey(Constant.NTP);
if (mbNtp == null) {
return cronPoints;
}
String cronValue = null;
String cornBefor = "0 ";
String cronEnd = " * * * ?";
cronValue = cornBefor + "0/" + mbNtp.getTbsj() + cronEnd;
return cronValue;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
String cron = getCronInfo();
logger.info("获取NTP定时任务配置:" + cron);
scheduledTaskRegistrar.addCronTask(new Runnable() {
@Override
public void run() {
Cypz cypz = cypzMapper.selectByPrimaryKey(Constant.SJZLPT);
//调用治理平台服务
try {
String getResult = HttpUtil
.createGet(cypz.getValuename() + "/PSPC/SC/System/getLocalTime")
.execute()
.charset("utf-8")
.body();
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = gson.fromJson(getResult, map.getClass());
String statusCode = (String) map.get("statusCode");
String localTime = (String) map.get("localTime");
if ("0".equals(statusCode)) {
ntpTime(localTime);
}
} catch (Exception e) {
logger.error("调用第三方ntp同步时间接口失败", e);
}
}
}, cron);
}
public void ntpTime(String synTime) {
logger.info("开始同步服务器时间为:" + synTime);
//需要同步的时间
//同步日期 格式 YYYY-MM-DD 也可以是 YYYYMMDD格式 这里是 2020-01-18 08:08:08
String cmd = "date -s " +"'"+ synTime+"'";
logger.info("更改服务器命令:" + cmd);
try {
Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
process.waitFor();
//查询同步后的时间
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String nowTime = null;
//输出操作结果
while ((nowTime = br.readLine()) != null) {
logger.info("同步后的日期为:" + nowTime);
}
} catch (IOException | InterruptedException e) {
logger.error("ntp同步时间错误", e);
}
}
}