




已阅读5页,还剩24页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
自己一直想做个定时任务工具,以前一直时间做,最近,在寝室,每天都为电脑连网烦恼,自己就花了时间做了一个定时自动运行程序的小工具,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 = ; 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 fut
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 小学汉字课标解读课件
- 血细胞直方图
- 小学生药品安全认知教育
- 信息技术键盘操作
- 小脑肿瘤手术配合
- 小细胞肺癌的诊治共识
- 导尿管相关尿路感染防控标准
- 小学实习汇报总结
- 细胞治疗展厅设计
- 销售季度业绩汇报
- GB/T 3098.15-2023紧固件机械性能不锈钢螺母
- 兰花花叙事曲二胡曲谱
- 调解协议书电子版5篇(可下载)
- 材料性能学(第2版)付华课件1-弹性变形
- GB/T 4909.4-2009裸电线试验方法第4部分:扭转试验
- PDCA质量持续改进案例一:降低ICU非计划拔管发生率
- 2023年烟台蓝天投资开发集团有限公司招聘笔试题库及答案解析
- 企业标准编写模板
- 初中道德与法治 九年级(维护祖国统一)初中道德与法治九年级作业设计样例
- 幼儿园绘本故事:《骄傲的大公鸡》 课件
- 江西省赣州市于都县2022-2023学年九年级化学第一学期期中监测试题含解析
评论
0/150
提交评论