c# - 在 C# 控制台应用程序中每 10 秒从 api 更新一次恒温器结果

标签 c# json api console-application

我需要帮助以每 10 秒从 thingspeak.io API 更新恒温器温度。我从 thingspeak channel 获取 JSON 数据,并将其转换并显示在控制台中。

到目前为止,这是我的代码

string url = "http://api.thingspeak.com/channels/135/feed.json";

WebClient webClient = new WebClient();
var data = webClient.DownloadString(url);
dynamic feed = JsonConvert.DeserializeObject<dynamic>(data);
List<dynamic> feeds = feed.feeds.ToObject<List<dynamic>>();
string field1 = feeds.Last().field1;
float temperature = float.Parse(field1, CultureInfo.InvariantCulture);

Console.WriteLine("----------CURRENT CHANNEL----------");
Console.WriteLine("\n");
Console.WriteLine("Channel name: " + feed.channel.name);
Console.WriteLine("Temperature: " + temperature.ToString() + " °C");
Console.WriteLine("\n");

int trenutna_temp = Convert.ToInt32(temperature);

Console.WriteLine("----------DEVICES----------");

if (trenutna_temp < 10)
{
    Console.WriteLine("turn on heating);
}
else if (trenutna_temp > 10 && trenutna_temp < 20)
{
    Console.WriteLine("turn off");
}
else if (trenutna_temp > 20)
{
    Console.WriteLine("Turn on cooling");
}
Console.ReadLine();

现在我想每 10 秒更新一次此数据。如果你们中的任何人能指出正确的方向或帮助我修复代码,我将不胜感激。

最佳答案

一种选择是使用 System.Threading.Timer:

public static void Main() 
{  
   System.Threading.Timer t = new System.Threading.Timer(UpdateThermostat, 5, 0, 2000); //10 times 1000 miliseconds
   Console.ReadLine();
   t.Dispose(); // dispose the timer
}


private static void UpdateThermostat(Object state) 
{ 
   // your code to get your thermostat
   //option one to print on the same line:
   //move the cursor to the beginning of the line before printing:
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(DateTime.Now);

   //option two to print on the same line:
   //printing "\r" moves cursor back to the beginning of the line so it's a trick:
    Console.Write("\r{0}",DateTime.Now);
}

Timer MSDN documentation here

关于c# - 在 C# 控制台应用程序中每 10 秒从 api 更新一次恒温器结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321026/

相关文章:

c# 在所有文件中最快的字符串搜索

c# - 如何在angularjs中使用ng-repeat渲染mathml?

c# - MVC6 - 如果(复选框勾选)则删除线

jquery - Jackson (JSON) 当 Float 为 null 时抛出 JsonMappingException

json - 如何通过VB.net传递复杂的JSON对象来调用Rest API

c# - 反射 - 如何在参数的指定索引处获取值

javascript - 控制台错误 - 解析 AJAX JSON 解析

java - 字符串到数组 Java 到 Json 对象

php - Facebook 注册和登录 Slim Framework PHP API

javascript - 如何从api服务器下载/保存json数据并在每个特定时间自动更新?