Time based Method execution in C#
I have a method send()
that I wish to execute/call every 1 second. I'm having difficulty implementing this. So far this is what I have come up with in my main program:
bool done = false;
while (!done)
{
string vCurrent = RandomVoltage(220, 240) + "" + RandomCurrent(10, 13);
int seconds = RandomSec();
if (isEven(seconds))
send(vCurrent, "169.254.156.135");//send the string to the ip address
}
So basically I try call my send()
method for every second of the current time that is even, and I skip the odd seconds, here is how I tried to implement that with my RandomSec()
and isEven()
methods:
private static readonly object syncLock = new object();
public static int RandomSec()
{
lock (syncLock)
{
return DateTime.Now.Second;
}
}
public static bool isEven(int sec)
{
if ((sec % 2) == 0)
return tr开发者_JAVA百科ue;
else return false;
}
Now the problem is when I run the while loop in my program, my send()
method sends a big bunch of strings in 1 second, then pauses for 1 second and then sends another big bunch of messages when the current second is even again. How can I get my program to execute my send()
method only ONCE every 1 second, so that the send()
method sends only 1 string every even second rather than say 20/30 of them. Is it possible for me to call my send()
method in a time controlled loop? Any help is greatly appreciated.
Thanks in advance.
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=VS.100).aspx
You can use the Timer class.
Sample Code from the above link:
public class Timer1
{
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 5 seconds.
aTimer.Interval=5000;
aTimer.Enabled=true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
}
It is much easier to send a string, wait/sleep for a second (or two) and then send the next one.
Polling on the time, many times per second, will cause the effect you are experiencing
精彩评论