2016-05-07 49 views
1

我有这种方法从API获取数据并将其保存到JSON文件中。C#在一段时间间隔内运行的方法

如何获取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); 
     } 
    } 
+0

你的主机是什么类型的? Winforms?安慰?网站? – user3185569

+0

我使用mvc。 –

+0

你可以试试[FluentScheduler](https://github.com/fluentscheduler/FluentScheduler) –

回答

2

使用定时器,在你的saveUsers()方法添加object source, ElapsedEventArgs e参数,使其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); 
+0

我需要它是一个mvc应用程序 –

+0

所以你想它从你的控制器启动计时器? – Mostafiz

+0

@RobelHaile看到我的最新更新,我已经展示了如何从'MVC'控制器启动计时器 – Mostafiz

1

使其成为控制台应用程序并使用Windows任务计划程序以任意频率调用它。

+0

我需要它作为mvc应用程序 –

+2

为什么?如果你需要其他东西的MVC,你可以同时拥有MVC应用程序和控制台应用程序。从你的代码看,它不需要(也不应该)在MVC应用程序上。 – pomber

相关问题