simple timer applications are not complex. You can set several parameters based on your own situation. The following Code :
Private voidRun (){TimercallbackTCB =NewTimercallback(Executerun); // The timer starts to run after 5 seconds (duetime), and then runs once every 1 second (period ).TimerTimer =NewTimer(TCB,Null, 5000,100 0 );}Private voidExecuterun (ObjectOBJ ){Console. Writeline ("Timer is running"+Datetime. Now. tostring ());}
In our scheduledjob project, some jobs adopt this method: Execute at a specified time;
However, in some cases, the execution of a job is not so regular. It may be executed once on the first day of every month, maybe on Monday, or at three o'clock every day, at three o'clock P.M,
At this time, you have to use another method for Timer: after a job is executed, calculate the time point to be executed next time based on the specified file, calculate the current and next execution time as duetime,
Change the duetime of timer. The following code demonstrates how to use the change method to change duetime.
Using System; Using System. Collections. Generic; Using System. Threading; Namespace Filesystemwatcherdemo { /// <Summary> /// demo timer duetime change /// </Summary> Class Timerdemo { Dictionary < String , Timer > Timerpool; Private int Duttime = 1; Static void Main ( String [] ARGs ){ Timerdemo Demo = New Timerdemo (); Demo. beginrun ();
Console . Read ();} Private void Beginrun () {timerpool = New Dictionary < String , Timer > (); For ( Int I = 1; I <= 1; I ++ ){ Timercallback TCB = New Timercallback (Execute ); // Timeout. Infinite specifies that the timer starts to run after duetime and only runs once. to execute it again, use the change method to re-specify the duetime Timer Timer =New Timer (TCB, I. tostring (), getduetime (duttime ), Timeout . Infinite); timerpool. Add (I. tostring (), timer );}} Private void Execute ( Object OBJ ){ String Ep = OBJ As string ; If (Ep! = Null ){ Console . Writeline ( "Timer" + EP +"Is running" + Datetime . Now. tostring ()); Timer Timer = timerpool [EP]; timer. Change (getduetime (duttime ++ ), Timeout . Infinite ); // Use the change method to re-specify duetime }} Private long Getduetime ( Int I ){ Return Convert . Toint64 (I * 1000 );}}}