C# Run method in a time interval [closed]

最后都变了- 提交于 2019-12-13 02:34:53

问题


I have this method that gets data from an api and saves it to a JSON file.

How can I get the JSON file to be updated every hour on the hour.

 public void saveUsers()
    {
        string  uri = "https://****dd.harvestapp.com/people";

        using (WebClient webClient = new WebClient())
        {
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.Accept] = "application/json";
            webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes(usernamePassword));

            string response = webClient.DownloadString(uri);

            File.WriteAllText(jsonPath, response);
        }
    }

回答1:


Use timer, add object source, ElapsedEventArgs e parameters in your saveUsers() method and make it static

private static System.Timers.Timer timer;

public static void Main()
{
    timer = new System.Timers.Timer(10000);

    timer.Elapsed += new ElapsedEventHandler(saveUsers);

    timer.Interval = 3600000;
    timer.Enabled = true;

}

 public static void saveUsers(object source, ElapsedEventArgs e)
    {
        string  uri = "https://****dd.harvestapp.com/people";
        using (WebClient webClient = new WebClient())
        {
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.Accept] = "application/json";
            webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes(usernamePassword));

            string response = webClient.DownloadString(uri);


            File.WriteAllText(jsonPath, response);

        }

    }

Update

Suppose you have a MVC controller name Home then you can start the timer from the index method

public class HomeController : Controller
    {
        private static System.Timers.Timer timer;
        public ActionResult Index()
        {
            timer = new System.Timers.Timer(10000);
            timer.Elapsed += new ElapsedEventHandler(saveUsers);
            timer.Interval = 3600000;
            timer.Enabled = true;

            return View();
        }
    }

And keep one thing in mind because you want to run the timer in an hour interval so may garbage collector stop the timer before method call, you need to keep alive the timer, you can keep timer alive this way after starting the timer

GC.KeepAlive(timer);



回答2:


Make it a console application and use Windows Task Scheduler to call it with any frequency you want.



来源:https://stackoverflow.com/questions/37090005/c-sharp-run-method-in-a-time-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!