📅  最后修改于: 2023-12-03 14:39:44.313000             🧑  作者: Mango
The System.Timers.Timer
class in C# provides a mechanism to raise an event at regular intervals. This can be useful in scenarios where you need to perform certain tasks periodically, such as updating data, retrieving information from remote servers, or running scheduled tasks.
Here is an example of how to set up a timer that executes a specific action every 30 seconds:
using System;
using System.Timers;
class Program
{
static void Main()
{
// Create a timer with an interval of 30 seconds
var timer = new Timer(30000);
// Hook up the Elapsed event
timer.Elapsed += TimerElapsed;
// Start the timer
timer.Start();
// Wait for user input to exit
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
// Stop the timer and release resources
timer.Stop();
timer.Dispose();
}
static void TimerElapsed(object sender, ElapsedEventArgs e)
{
// Perform the desired action here
Console.WriteLine("Timer elapsed. Performing task...");
}
}
In the above code snippet, we create a Timer
object and set its interval to 30 seconds (30,000 milliseconds). We then attach an event handler method (TimerElapsed
) to the Elapsed
event of the timer. This event will be raised every time the specified interval has elapsed.
Inside the TimerElapsed
method, you can include the code that needs to be executed when the timer elapses. In this example, we simply print a message to the console.
The program runs indefinitely until the user presses any key. Once a key is pressed, we stop the timer and release any resources associated with it.
By adjusting the interval and modifying the code inside the TimerElapsed
method, you can customize the behavior of the timer to suit your specific requirements.
Remember to include the necessary using directives (using System;
and using System.Timers;
) at the beginning of your code file to access the required classes and avoid compile errors.