Reputation: 2633
I am required to create a function that will run every 5 second no matter what is the outcome , I go through the MSDN library and found out this http://msdn.microsoft.com/en-us/library/yz1c7148.aspx , I think this is what I need , but I need to know more about the due time and period parameters
For my understanding:- DueTime is it the time that will wait before start the timer ? Periodtime is it time that repeat the time ?
my question is whether my understanding is correct regarding the Timer provide by msdn. besides , if I want to set my time runn every 5 second no matter the previous timer is complete or not what should I set it ?
Upvotes: 0
Views: 3497
Reputation: 664
You are absolutely correct in your understanding. The following code should do what you want:
System.Threading.Timer timer = new System.Threading.Timer(Callback, null, 0, 5 * 1000);
however I should mention what System.Threading.Timer is not quite accurate and there will be some accumulating error on each call. For example the following code
static void Main(string[] args)
{
System.Threading.Timer timer = new System.Threading.Timer(Callback, null, 0, 1 * 1000);
Console.ReadLine();
}
static void Callback(object state)
{
Console.WriteLine(DateTime.Now.ToString("hh:MM:ss:ffff"));
}
produces the following result on my computer:
03:10:14:8014
03:10:15:8154
03:10:16:8294
03:10:17:8434
03:10:18:8574
03:10:19:8714
03:10:20:8854
03:10:21:8994
03:10:22:9134
03:10:23:9274
03:10:24:9414
03:10:25:9554
03:10:26:9694
03:10:27:9834
03:10:28:9974
03:10:30:0114
03:10:31:0254
Upvotes: 1
Reputation: 3685
just create a dummy timer to tick every five seconds and then launch your function in Tick
event using BeginInvoke
.
Upvotes: 1