C#做定时计划任务软件教程.doc
《C#做定时计划任务软件教程.doc》由会员分享,可在线阅读,更多相关《C#做定时计划任务软件教程.doc(29页珍藏版)》请在装配图网上搜索。
自己一直想做个定时任务工具,以前一直时间做,最近,在寝室,每天都为电脑连网烦恼,自己就花了时间做了一个定时自动运行程序的小工具,C#winform程序先看一下它的界面:这里面知识点还比较多,下面动手一步一步做,也不难的。新建一个窗体应用程序项目,我的项目名就是:新建一个接口,ISchedule.cs内容如下:using System;using System.Collections.Generic;using System.Text;namespace 定时任务工具 /任务计划接口和一些标准实现 #region 任务计划接口和一些标准实现 / / 计划的接口 / public interface ISchedule / / 返回最初计划执行时间 / DateTime ExecutionTime get; set; / / 初始化执行时间于现在时间的时间刻度差 / long DueTime get; / / 循环的周期 / long Period get; #endregion再新建一个类,CycExecution.cs 定义执行定时任务计划的相关参数,内容如下:using System;using System.Collections.Generic;using System.Text;namespace 定时任务工具 / / 周期性的执行计划 / public class CycExecution : ISchedule / / 构造函数,在一个将来时间开始运行 / / 计划执行的时间 / 周期时间 public CycExecution(DateTime shedule, TimeSpan period) m_schedule = shedule; m_period = period; / / 构造函数,马上开始运行 / / 周期时间 public CycExecution(TimeSpan period) m_schedule = DateTime.Now; m_period = period; private DateTime m_schedule; private TimeSpan m_period; /ISchedule 成员 #region ISchedule 成员 public long DueTime get long ms = (m_schedule.Ticks - DateTime.Now.Ticks) / 10000; if (ms 0) ms = 0; return ms; public DateTime ExecutionTime get / TODO: 添加 CycExecution.ExecutionTime getter 实现 return m_schedule; set m_schedule = value; public long Period get / TODO: 添加 CycExecution.Period getter 实现 return m_period.Ticks / 10000; #endregion 再新建一个具体实现定时器任务的类,Task.cs 内容如下:using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace 定时任务工具 / / 计划任务基类 / 启动的任务会在工作工作线程中完成,调用启动方法后会立即返回。 / / 用法: / (1)如果你要创建自己的任务,需要从这个类继承一个新类,然后重载Execute(object param)方法 / 实现自己的任务,再把任务加入到任务管理中心来启动和停止。 / 比如: / TaskCenter center = new TaskCenter(); / Task newTask = new Task( new ImmediateExecution(); / center.AddTask(newTask); / center.StartAllTask(); / (2)直接把自己的任务写入TimerCallBack委托,然后生成一个Task类的实例, / 设置它的Job和JobParam属性,再Start就可以启动该服务了。此时不能够再使用任务管理中心了。 / 比如: / Task newTask = new Task( new ImmediateExecution(); / newTask.Job+= new TimerCallback(newTask.Execute); / newTask.JobParam = Test immedialte task; /添加自己的参数 / newTask.Start(); / / public class Task /*/ / / 构造函数 / / 为每个任务制定一个执行计划 public Task(ISchedule schedule) if (schedule = null) throw (new ArgumentNullException(schedule); m_schedule = schedule; /*/ / / 启动任务 / public void Start() /启动定时器 m_timer = new Timer(m_execTask, m_param, m_schedule.DueTime, m_schedule.Period); /*/ / / 停止任务 / public void Stop() /停止定时器 m_timer.Change(Timeout.Infinite, Timeout.Infinite); /*/ / / 任务内容 / / 任务函数参数 public virtual void Execute(object param) /你需要重载该函数,但是需要在你的新函数中调用base.Execute(); m_lastExecuteTime = DateTime.Now; if (m_schedule.Period = Timeout.Infinite) m_nextExecuteTime = DateTime.MaxValue; /下次运行的时间不存在 else TimeSpan period = new TimeSpan(m_schedule.Period * 1000); m_nextExecuteTime = m_lastExecuteTime + period; /*/ / / 任务下执行时间 / public DateTime NextExecuteTime get return m_nextExecuteTime; DateTime m_nextExecuteTime; /*/ / / 执行任务的计划 / public ISchedule Shedule get return m_schedule; private ISchedule m_schedule; /*/ / / 系统定时器 / private Timer m_timer; /*/ / / 任务内容 / public TimerCallback Job get return m_execTask; set m_execTask = value; private TimerCallback m_execTask; /*/ / / 任务参数 / public object JobParam set m_param = value; private object m_param; /*/ / / 任务名称 / public string Name get return m_name; set m_name = value; private string m_name; /*/ / / 任务描述 / public string Description get return m_description; set m_description = value; private string m_description; /*/ / / 该任务最后一次执行的时间 / public DateTime LastExecuteTime get return m_lastExecuteTime; private DateTime m_lastExecuteTime; 再定义一个可以同时进行多个task任务的类,TaskCenter.cs 内容如下:using System;using System.Collections.Generic;using System.Text;using System.Collections;using System.Threading;/using NUnit.Framework; namespace 定时任务工具 / / 任务管理中心 / 使用它可以管理一个或则多个同时运行的任务 / / TestFixture public class TaskCenter /*/ / 构造函数 / public TaskCenter() m_scheduleTasks = new ArrayList(); /*/ / 添加任务 / / 新任务 public void AddTask(Task newTask) m_scheduleTasks.Add(newTask); /*/ / 删除任务 / / 将要删除的任务,你可能需要停止掉该任务 public void DelTask(Task delTask) m_scheduleTasks.Remove(delTask); /*/ / 启动所有的任务 / public void StartAllTask() foreach(Task task in ScheduleTasks) StartTask(task); /*/ / 启动一个任务 / / public void StartTask(Task task) /标准启动方法 if(task.Job = null) task.Job+= new TimerCallback(task.Execute); task.Start(); /*/ / 终止所有的任务 / public void TerminateAllTask() foreach(Task task in ScheduleTasks) TerminateTask(task); /*/ / 终止一个任务 / / public void TerminateTask(Task task) task.Stop(); /*/ / 获得所有的 / ArrayList ScheduleTasks get return m_scheduleTasks; private ArrayList m_scheduleTasks; /*/ / 单元测试代码 / / Test /public void TestTaskCenter() / / TaskCenter center = new TaskCenter(); / /Test immedialte task / Task newTask = new Task( new ImmediateExecution(); / newTask.Job+= new TimerCallback(newTask.Execute); / newTask.JobParam = Test immedialte task; / /Test excute once task / DateTime sheduleTime = DateTime.Now.AddSeconds(10); / ScheduleExecutionOnce future= new ScheduleExecutionOnce(sheduleTime); / Task sheduleTask = new Task( future); / sheduleTask.Job+= new TimerCallback(sheduleTask.Execute); / sheduleTask.JobParam = Test excute once task; / /Test cyc task at once / CycExecution cyc = new CycExecution( new TimeSpan(0,0,2); / Task cysTask = new Task(cyc); / cysTask.Job+= new TimerCallback(cysTask.Execute); / cysTask.JobParam = Test cyc task; / /Test cys task at schedule / CycExecution cycShedule = new CycExecution( DateTime.Now.AddSeconds(8),new TimeSpan(0,0,2); / Task cycSheduleTask = new Task(cycShedule); / cycSheduleTask.Job+= new TimerCallback(cysTask.Execute); / cycSheduleTask.JobParam = Test cyc Shedule task; / center.AddTask(newTask); / center.AddTask(sheduleTask); / center.AddTask(cysTask); / center.AddTask(cycSheduleTask); / center.StartAllTask(); / Console.ReadLine(); / Console.WriteLine(newTask.LastExecuteTime); / 再建立一个操作文件的类,用来保存定时任务的参数,不然每次都输入,谁还愿意用呀,这么麻烦,这里,建立一个类,MyConfig.cs (其实在C#里面,类的文件名和里面的具体类名没有关系的,这一点要搞清楚),这个MyConfig.cs文件里有几个类,内容如下:using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Text.RegularExpressions;namespace 定时任务工具 public class ConfigFile : IConfig/文件操作类,继承自接口,主要就是利用 类名索引这个特点,方便存储数据,后面看一下用怎么用就懂了。 / Fields private string _fileName = ; private static ConfigFile _Instance; / Methods private ConfigFile() public bool CreateFile() bool flag = false; if (File.Exists(this.fileName) return flag; using (File.Create(this.fileName) return true; public bool KeyExists(string Key) return (this.Keys as ICollection).Contains(Key); / Properties public string fileName get return this._fileName; set this._fileName = value; public static ConfigFile Instanse get if (_Instance = null) _Instance = new ConfigFile(); return _Instance; public string thisstring Key get if (!this.CreateFile() foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8) Match match = Regex.Match(str, (w+)=(wW+); string str2 = match.Groups1.Value; string str3 = match.Groups2.Value; if (str2 = Key) return str3; return ; set if (this.CreateFile() File.AppendAllText(this.fileName, Key + = + value + rn); else string contents = File.ReadAllLines(this.fileName, Encoding.UTF8); for (int i = 0; i contents.Length; i+) string input = contentsi; Match match = Regex.Match(input, (w+)=(w+); string str2 = match.Groups1.Value; string text1 = match.Groups2.Value; if (str2 = Key) contentsi = str2 + = + value; File.WriteAllLines(this.fileName, contents); return; File.AppendAllText(this.fileName, Key + = + value + rn); public string Keys get List list = new List(); if (!this.CreateFile() foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8) string item = Regex.Match(str, (w+)=(w+).Groups1.Value; list.Add(item); return list.ToArray(); public interface IConfig/接口 / Methods bool KeyExists(string Key); / Properties string thisstring Key get; set; string Keys get; 做到这一步,后台执行定时任务的类已经写好了,下面就是界面的问题了。后台代码:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;using System.Diagnostics;using System.IO;using Microsoft.Win32;using System.Runtime.InteropServices;namespace 定时任务工具 public partial class Form1 : Form TaskCenter center = new TaskCenter(); IConfig cf = ConfigFile.Instanse; Task cycSheduleTask; public Form1() InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; #region Form1_Load private void Form1_Load(object sender, EventArgs e) LoadConfig(); if (cfStartTaskAtProgrameRun = 1) StartTaskFunc(); #endregion #region LoadConfig / / 加载配置文件中的信息 / protected void LoadConfig() try string path = AppDomain.CurrentDomain.BaseDirectory; ConfigFile.Instanse.fileName = path + 定时任务设置.ini; cfAuthor = pukuiminqq.com; txtProgramePath.Text = cfProgramePath; txtProcess.Text = cfProcessName; string setedtime = cfScheduleTime; txtTaskTime.Text = setedtime != ? DateTime.Now.ToString(yyyy-MM-dd ) + Convert.ToDateTime(setedtime).ToString(HH:mm:ss) : DateTime.Now.ToString(); numHour.Value = Convert.ToDecimal(cfHours); numMinute.Value = Convert.ToDecimal(cfMinutes); numSecond.Value = Convert.ToDecimal(cfSeconds); cbStartAtConfig.Checked = cfStartAtWindowStart = 1 ? true : false; cbStartTaskAtProgrameRun.Checked = cfStartTaskAtProgrameRun = 1 ? true : false; EndTask.Enabled = false; trackBar1.Value = 90; catch (Exception er) MessageBox.Show(读取程序配置文件出错,请重新设置各选择,请不要随意手动修改配置文件,谢谢!rn + er.Message); #endregion #region TestTaskCenter protected void TestTaskCenter(schedule sd) #region 测试其它任务的代码 /Test immedialte task /Task newTask = new Task(new ImmediateExecution(); /newTask.Job += new TimerCallback(newTask.Execute); /newTask.Job += new TimerCallback(test1); /newTask.JobParam = Test immedialte task; /Test excute once task /DateTime sheduleTime = DateTime.Now.AddSeconds(10); /ScheduleExecutionOnce future = new ScheduleExecutionOnce(sheduleTime); /Task sheduleTask = new Task(future); /sheduleTask.Job += new TimerCallback(sheduleTask.Execute); /sheduleTask.JobParam = Test excute once task; /Test cyc task at once /CycExecution cyc = new CycExecution(new TimeSpan(0, 0, 2); /Task cysTask = new Task(cyc); /cysTask.Job += new TimerCallback(cysTask.Execute); /cysTask.JobParam = Test cyc task; #endregion /Test cys task at schedule int hour = Convert.ToInt32(sd.hours); int minute = Convert.ToInt32(sd.minutes); int second = Convert.ToInt32(sd.seconds); CycExecution cycShedule = new CycExecution(Convert.ToDateTime(sd.ScheduleTime), new TimeSpan(hour, minute, second); cycSheduleTask = new Task(cycShedule); cycSheduleTask.Job += new TimerCallback(MySchedule); cycSheduleTask.JobParam = sd; center.AddTask(cycSheduleTask);/可以加入很多任务 center.StartAllTask();/开始所有加入的任务 /Console.WriteLine(newTask.LastExecuteTime); / MessageBox.Show(newTask.LastExecuteTime.ToString(); #endregion #region MySchedule protected void MySchedule(object obj) /C:Program Files锐捷网络Ruijie SupplicantRuijieSupplicant.exe- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# 定时 计划 任务 软件教程
装配图网所有资源均是用户自行上传分享,仅供网友学习交流,未经上传用户书面授权,请勿作他用。
关于本文