'Update database with Json API data on interval ASP.NET Core MVC

I am trying to get temperature readings from a raspberry pi API once every 5 minutes.

Currently, when I refresh my homepage, it calls the API for each of my temperature sensors. It takes about 3 seconds for the page to load, which I am okay with, but would rather have some sort of background task that runs every 5 minutes and saves the data from the API call to my database. This way I have a nice log of the temperatures and can see variations.

This is what I want to run every 5 minutes. I don't have much experience with API's so I' not certain what the best way to accomplish this would be (PS: this is meant to run either on linux or a second raspberry pi)

foreach (var sensor in TempSensors) //for each one sensor get a reading from the api and save it
{
    var cookieName = api.CookieName;
    var cookieString = api.Cookie;
    var url = "apiurl";
    var baseAddress = new Uri(url);
    var cookieContainer = new CookieContainer();

    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
    {
       var message = new HttpRequestMessage(HttpMethod.Get, "/api/" + sensorId + "/read")                      
       message.Headers.Add("Accept", "application/json");

       cookieContainer.Add(baseAddress, new Cookie(cookieName, cookieString));
       HttpResponseMessage response = await client.GetAsync(message.RequestUri); // call the api and get the reading

       if (response.StatusCode == HttpStatusCode.OK)
       {
          var content = await response.Content.ReadAsStringAsync();
          TempReading tr = new TempReading(); // make a new reading
          tr.TempSensorId = sensorId.ToString(); //set its sensor id to the current sensor id     
          tr.TempReadingDate = DateTime.Now; // set the read time to right now
          tr.Value = content.ToString(); // write the reading to a string
          await Create(tr); //add it to the db                            
       }
   }
}


Solution 1:[1]

Thanks for the reply @Brando , I actually decided to just use quartz to startup a recurring task at startup and its working great. I started to go with the Service worker route, but it seemed to be quite a bit more effort than just using the Quartz.Net package.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user7704925