簡體   English   中英

如何在C#中使用計時器?

[英]How to use timer in C#?

我希望每2秒執行一次我的函數,以檢查是否有任何新用戶,以便為他們創建新日志。 這是在控制台應用程序中,所以我使用了線程。 但是我的控制台在運行一次功能后關閉了。 我希望計時器能夠一直運行到控制台,並且我的createLog函數將每2秒執行一次。 我是C#的新手,所以也許我的計時器概念完全錯誤。 請幫忙...

namespace ConsoleApplication1
{
    class Program
    {
        public static Hashtable clientsList = new Hashtable();


        static void Main(string[] args)
        {
            Timer t = new Timer(createLog, null, 0, 2000);


            IPAddress ip = IPAddress.Parse("127.0.0.1");
            TcpListener serverSocket = new TcpListener(ip, 9888);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            .... //this main is monitoring the network....
           console.read();
        }



 private static void createLog(object state)
        {
         //this function checks the database and if there is new user it will create a new text file for he/she. 

        }
  }

由於這是一個控制台應用程序,因此您需要添加類似Console.ReadLine()以使該應用程序保持活動狀態,直到用戶希望將其關閉。

網上有很多關於如何使用計時器的教程。請仔細閱讀它,然后研究您的代碼,以獲取可能犯的錯誤。 試試這個鏈接: http : //www.dotnetperls.com/timer

也許FluentScheduler可以提供幫助。

using FluentScheduler;

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        // Schedule an ITask to run at an interval
        Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds();

        // Schedule a simple task to run at a specific time
        Schedule(() => Console.WriteLine("Timed Task - Will run every day at 9:15pm: " + DateTime.Now)).ToRunEvery(1).Days().At(21, 15);

        // Schedule a more complex action to run immediately and on an monthly interval
        Schedule(() =>
        {
            Console.WriteLine("Complex Action Task Starts: " + DateTime.Now);
            Thread.Sleep(1000);
            Console.WriteLine("Complex Action Task Ends: " + DateTime.Now);
        }).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
    }
}

在調用Start之后,您需要一個類似Console.ReadLine的阻塞調用來保持前台線程運行。 另外,您的計時器有資格進行垃圾回收,因為它在創建后不再被引用。 在Main方法的末尾使用GC.KeepAlive以防止計時器被GC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM