In a business complex application, it is sometimes required that one or more tasks are scheduled at a certain time or at a certain time interval, such as scheduled backups or synchronization of databases, sending emails regularly, etc., which we call scheduled tasks.
Timing task Scheduling Implementation method:
1.Windows Service Implementation 2.WebApplication Timer timer task Schedule 3.Windows scheduled Task
But 1,3 can be implemented at a certain time, 2 can only be implemented at a certain time interval.
WebApplication Way:
(1) Thread mode (open threads):
public class Datetimeclass {public void Parse () {while (true) { int time = Int. Parse (DateTime.Now.ToString ("SS")); Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + " --- " + time); Thread.Sleep (3*1000);//Perform task once every 3 seconds } } public void Consolewirte () { ThreadStart ThreadStart = new ThreadStart (this. Parse); Thread thread = new Thread (ThreadStart); Thread. Start (); } } Class program { static void Main (string[] args) { new Datetimeclass (). Consolewirte (); } }
(2) Timer mode:
Using timer = System.timers.timer;class program {static void Main (string[] args) { Timer timer=new timer (); timer. Interval = 10000; Timer. Enabled = true; Timer. Elapsed + = timer_elapsed; Console.readkey (); } static void Timer_elapsed (object sender, System.Timers.ElapsedEventArgs e) { new Datetimeclass (). Consolewirte (); }} public class Datetimeclass {public void Consolewirte () { //threadstart ThreadStart = new ThreadStart (this. Parse); Thread thread = new Thread (ThreadStart); Thread. Start (); Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + " --- " + 1); } }
Timed Task Scheduling