简体   繁体   中英

How to use timer in C#?

I want my function to be executed every 2 seconds to check if there is any new user so that I could make a new log for them. This is in console application so i used Thread. But my console shut down after it run the function once. I am expecting the timer to run as long as I am running the console and my createLog function will be executed every 2 seconds. I am relatively new to C# so maybe my concept of timer is completely wrong. Please help...

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()以使该应用程序保持活动状态,直到用户希望将其关闭。

There are lots of tutorials available over the net ,about how to use the timers.Please go through it and then study your code ,to get the mistake you might have made. Try this link : http://www.dotnetperls.com/timer

Maybe FluentScheduler can help.

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

You need a blocking call like Console.ReadLine after calling Start to keep the foreground thread running. Also, the your Timer is eligible for garbage collection because it is not referenced again after it is created. Use GC.KeepAlive at the end of the Main method to prevent the timer from being GC'd.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM