C#服務(wù)實(shí)現(xiàn)簡單的定時(shí)任務(wù)
C#定時(shí)任務(wù)開發(fā)System.Timers.Timer()使用
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using TxtControl; using DataControl; using System.Configuration;
namespace WinFormSendSMS { public partial class SendSMS : Form { private System.Timers.Timer theTimer = new System.Timers.Timer();//定時(shí)器 private double timespan;//服務(wù)執(zhí)行的時(shí)間間隔 public SendSMS() { InitializeComponent(); } private void btnStart_Click(object sender, EventArgs e) { try { TxtCommon tcomm = new TxtCommon(); DataUtility dUtility = new DataUtility(); this.theTimer.Elapsed = new System.Timers.ElapsedEventHandler(this.theTimer_Elapsed); timespan = Convert.ToDouble(ConfigurationManager.AppSettings["Minute"]); theTimer.Interval = timespan * 60 * 1000; //轉(zhuǎn)換為毫秒 theTimer.Enabled = true; theTimer.Start(); this.btnStart.Enabled = false; this.btnStart.Text = "已啟動(dòng)..."; btnStop.Enabled = true; } catch (Exception ex) { MessageBox.Show("error:" ex.Message); } } /// <summary> /// 定時(shí)任務(wù)處理過程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void theTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { LogMgr.WriteLine("--====定時(shí)開始執(zhí)行程序!===-----"); TxtCommon tcomm = new TxtCommon(); DataUtility dUtility = new DataUtility(); //接收A8表里的數(shù)據(jù),放到list List<SMSEntity> orginalList = A8DataControl.SMSList(); LogMgr.WriteLine("獲得" orginalList.Count "條數(shù)據(jù)"); if (orginalList.Count > 0) { ProcessSMS process = new ProcessSMS(); process.ProcessInfo(orginalList); } LogMgr.WriteLine("--====定時(shí)開始執(zhí)行程序!end===-----"); } catch (Exception ex) { LogMgr.WriteLine("定時(shí)開始執(zhí)行程序出現(xiàn)異常:" ex.Message); } } /// <summary> /// 關(guān)閉定時(shí)任務(wù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStop_Click(object sender, EventArgs e) { this.theTimer.Enabled = false; this.btnStart.Enabled = true; this.btnStart.Text = "開啟"; btnStop.Enabled = false; } } }
原文鏈接:C#服務(wù)實(shí)現(xiàn)簡單的定時(shí)任務(wù) C#定時(shí)任務(wù)開發(fā)