C#在一个时间间隔内运行方法

时间:2016-05-07 14:56:58

标签: c# .net asp.net-mvc asp.net-web-api timer

我有这个方法从api获取数据并将其保存到JSON文件。

如何让JSON文件每小时更新一次。

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

2 个答案:

答案 0 :(得分:2)

使用计时器,在object source, ElapsedEventArgs e方法中添加saveUsers()参数并将其设为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);

        }

    }

<强>更新

假设您有一个MVC控制器名称Home,那么您可以从index方法启动计时器

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

并且记住一件事因为你想要在一小时的时间间隔内运行计时器,所以垃圾收集器可能会在方法调用之前停止计时器,你需要保持计时器的活动,你可以在启动计时器之后保持计时器的活动状态

GC.KeepAlive(timer);

答案 1 :(得分:1)

将其设为控制台应用程序并使用Windows任务计划程序以您想要的任何频率调用它。