2016-05-07 10 views
1

このメソッドは、APIからデータを取得してJSONファイルに保存するメソッドです。C#時間間隔でメソッドを実行する

JSONファイルを1時間ごとに更新するにはどうすればよいですか。

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

タイマーを1時間間隔で実行したいので、ガベージコレクタがメソッド呼び出しの前にタイマーを停止させる可能性があるため、タイマーを維持しておく必要があります。起動後にタイマーをこのまま生き続けることができますタイマー

GC.KeepAlive(timer); 
+0

を試すことができます。私はそれがあなたのコントローラからタイマーを開始したいので、mvcアプリケーション –

+0

にする必要がありますか? – Mostafiz

+0

@RobelHaile私の最新のアップデートを見て、どのように 'MVC'コントローラからタイマーを始めることができますか – Mostafiz

1

は、コンソールアプリケーション作成し、あなたが望む任意の周波数でそれを呼び出すためにWindowsのタスクスケジューラを使用します。

+0

MVCアプリケーションにする必要があります –

+2

なぜですか?他のものにMVCが必要な場合は、MVCアプリケーションとコンソールアプリケーションの両方を使用できます。あなたのコードから、それはMVCアプリケーション上にある必要もない(そうすべきではありません)ように見えません。 – pomber

関連する問題