C# Run method in a time interval [closed]

2019-08-01 04:42发布

问题:

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.