2016-07-19 1 views
0

나는 1, 5, 30 분 또는 매시간 사용자에게 알리는 응용 프로그램을 만들고 있습니다. 예를 들어 사용자가 5:06에 프로그램을 열면 프로그램이 6:06에 사용자에게 알립니다.C#에서 1 분마다 시간 확인하기

그래서 내 현재 코드는 Thread.Sleep() 함수를 사용하여 5 분마다 사용자에게 알려주고 있지만, 다소 불편 함을 느낍니다.

public void timeIdentifier() 
    { 
     seiyu.SelectVoiceByHints(VoiceGender.Female); 
     while(true) 
     { 
      string alarm = String.Format("Time check"); 
      seiyu.Speak(alarm); 
      string sayTime = String.Format(DateTime.Now.ToString("h:mm tt")); 
      seiyu.Speak(sayTime); 
      // It will sleep for 5 minutes LOL 
      Thread.Sleep(300000); 
     } 
    } 
+1

왜 당신이 알아 방금 여기 내 대답에 제안 – Vicky

+0

봐위한 작업 Schedular를 사용 해달라고 (A의 구현입니다 RecurrentCancellableTask)를 사용하면 문제를 쉽게 해결할 수 있습니다. http://stackoverflow.com/questions/7472013/how-to-create-a-thread-task-with-a-continuous-loop/35308832#35308832 – Juan

+1

' 타이머 ' –

답변

5

대신 Thread.Sleep()의 타이머를 사용할 수 있습니다 :

public class Program 
{ 
    private static System.Timers.Timer aTimer; 

    public static void Main() 
    { 
     aTimer = new System.Timers.Timer(5000); // interval in milliseconds (here - 5 seconds) 

     aTimer.Elapsed += new ElapsedEventHandler(ElapsedHandler); // handler - what to do when 5 seconds elaps 

     aTimer.Enabled = true; 

     // If the timer is declared in a long-running method, use 
     // KeepAlive to prevent garbage collection from occurring 
     // before the method ends. 
     //GC.KeepAlive(aTimer); 
    } 

    //handler 
    private static void ElapsedHandler(object source, ElapsedEventArgs e) 
    { 
     string alarm = String.Format("Time check"); 
     seiyu.Speak(alarm); 
     string sayTime = String.Format(DateTime.Now.ToString("h:mm tt")); 
     seiyu.Speak(sayTime); 
    } 
} 
+0

더 이상 할 방법이 있습니까? 루핑하고 값과 물건을 증가시키는 것과 같은가? – Kurogami

0

당신은 타이머 객체를 사용할 수 있습니다 (하여 System.Threading)

이 내 코드입니다. 타이머 개체에 시간 초과가없는 간격이 있습니다. 당신이 새로운 좋아하는 경우에

static void Main(string[] args) 
    { 
     int firstCallTimeOut = 0; 
     int callInterval = 300000; 
     object functionParam = new object();//optional can be null 
     Timer timer = new Timer(foo,null,firstCallTimeOut,callInterval); 

    } 
    static void foo(object state) 
    { 
     //TODO 
    } 
+1

가비지 컬렉터는 결국 로컬 객체에 대한 참조를 제거합니다. 따라서 일반적으로 타이머는 클래스 필드를 사용해야합니다. –

0

.NET TPL 구문 요이처럼 쓸 수 있습니다 :

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     Repeat(TimeSpan.FromSeconds(10)); 
     Console.ReadKey(); 
    } 

    private static void Repeat(TimeSpan period) 
    { 
     Task.Delay(period) 
      .ContinueWith(
       t => 
       { 
        //Do your staff here 
        Console.WriteLine($"Time:{DateTime.Now}"); 
        Repeat(period); 
       }); 
    } 
} 
관련 문제