You can use Windows Services to regularly execute one of the three methods, windows three methods
Method 1: Use the System. Timers. Timer
Public partial class Service1: ServiceBase {private UnitOfWork unitOfWork; private System. timers. timer timer1; // initialize a Timer LogHelper lghelper = new LogHelper (typeof (Service1); public Service1 () {InitializeComponent (); unitOfWork = new UnitOfWork (); this. timer1 = new System. timers. timer (); this. timer1.Interval = 1000; // set the timer start interval this. timer1.Elapsed + = new System. timers. elapsedEventHandler (timer1_Elapsed); // Method for timer scheduled execution} protected override void OnStart (string [] args) {this. timer1.Enabled = true; // enable the timer lghelper when the service starts. info ("service start");} protected override void OnStop () {this. timer1.Enabled = false; // disable the timer unitOfWork when the service is stopped. dispose (); lghelper. info ("Service stopped");} private void timerreceivelapsed (object sender, System. timers. elapsedEventArgs e) {this. timer1.Enabled = false; // disable the timer when the service is running, avoid restarting the timer at the timer time interval when the service is not finished (for example, if the timer is set to synchronize data once every 5 minutes, when the data volume is large, it cannot be synchronized within 5 minutes, when the timer interval is reached, synchronization starts again, so the timer is disabled when the service starts running) lghelper. info ("service starts running"); try {DoWork () ;}catch (Exception ex) {lghelper. error (ex. toString (); lghelper. info ("service failed"); Thread. sleep (5000);} this. timer1.Enabled = true; // The Service stops running and restarts the timer }}
Method 2: Use Task
Partial class Service2: ServiceBase, IDisposable {LogHelper lghelper = new LogHelper (typeof (Service2); private CancellationTokenSource TokenSource = new partition (); protected UnitOfWork unitOfWork = new UnitOfWork (); task MainTask; public Service2 () {InitializeComponent ();} public void Dispose () {unitOfWork. dispose ();} protected override void OnStart (string [] args) {lghelper. Info ("enable service! "); MainTask = Task. factory. startNew () => {while (true) {try {DoWork ();} catch (Exception ex) {lghelper. error (ex. toString (); Thread. sleep (60x60x1000);} Thread. sleep (5*60*1000) ;}}) ;}protected override void OnStop () {if (MainTask! = Null) {if (MainTask. Status = TaskStatus. Running) {}{ TokenSource. Cancel (); lghelper. Info ("thread end ");}}}}
Method 3: This method is easy to see and has never been used.
Http://www.cnblogs.com/ldyblogs/p/timer.html