class UpdateVideoTokenHelper
{
private static Timer myTimer;
private static string appKey = ConfigurationManager.AppSettings["appKey"];
private static string appSecret = ConfigurationManager.AppSettings["appSecret"];
public static void SetTimer()
{
myTimer = new Timer(10000);
myTimer.Elapsed += OnTimedEvent;
myTimer.AutoReset = true;
myTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
long updateTime = UpdateToken();
Timer timer = source as Timer;
if (updateTime > 0)
{
timer.Interval = updateTime;
}
else
{
timer.Interval = 432000;
}
}
private static long UpdateToken()
{
try
{
WebClient webClient = new WebClient();
string postString = "appKey=" + appKey + "&appSecret=" + appSecret;
//以form表单的形式上传
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// 转化成二进制数组
byte[] postData = Encoding.ASCII.GetBytes(postString);
// 上传数据
byte[] responseData = webClient.UploadData("https://open.ys7.com/api/lapp/token/get", "POST", postData);
string res = Encoding.UTF8.GetString(responseData);
var jsonObj = JObject.Parse(JsonConvert.DeserializeObject(res).ToString());
if (jsonObj["code"].ToString() == "200")
{
string accessToken = jsonObj["data"]["accessToken"].ToString();
string sql = "update FM_DEVICE set EXTENDCODE5 = '" + accessToken + "'";
int excuteRes = DBHelper.ExecuteCommand(sql);
}
//计算出需要更新的时间 修改timer 执行时间
long expireTime = long.Parse(jsonObj["data"]["expireTime"].ToString());
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
long nowTime = (DateTime.Now.Ticks - startTime.Ticks) / 10000;
return expireTime - nowTime;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return 20000;
}
}
}