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; } } }