C#实现定时任务Task Scheduler的示例代码
作者:我只吃饭不洗碗
这篇文章主要为大家详细介绍了C#实现定时任务Task Scheduler的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
本文和大家分享一个自己写的 Windows 定时任务计划(Task Scheduler) 动态创建代码,没做太多封装,留个实现笔记
首先封装一个简单配置项的类
核心代码
public class TaskSchedulerConfig { /// <summary> /// 引用程序路径 /// </summary> public string ApplicationPath { get; set; } /// <summary> /// 引用程序参数 /// </summary> //public string ApplicationParameter { get; set; } /// <summary> /// 任务名称 /// </summary> public string TaskName { get; set; } /// <summary> /// 任务说明 /// </summary> public string TaskDescription { get; set; } /// <summary> /// 任务执行周期 0 每日执行 1 每周执行 2 每月执行 /// </summary> public int TaskExecutionCycle { get; set; } /// <summary> /// 开始执行时间范围 yyyy/MM/dd HH:mm:ss /// </summary> public DateTime StartBoundary { get; set; } /// <summary> /// 每月的第几号执行 /// </summary> public int DaysOfMonth { get; set; } /// <summary> /// 每周的周几执行 /// </summary> public int DaysOfWeek { get; set; } }
两个范围判定的方法
/// <summary> /// 根据数字1-7来设置周一 - 周日 /// </summary> /// <param name="num"></param> /// <returns></returns> static DaysOfTheWeek GetDaysOfTheWeek(int num) { switch (num) { case 1: return DaysOfTheWeek.Monday; case 2: return DaysOfTheWeek.Tuesday; case 3: return DaysOfTheWeek.Wednesday; case 4: return DaysOfTheWeek.Thursday; case 5: return DaysOfTheWeek.Friday; case 6: return DaysOfTheWeek.Saturday; case 7: return DaysOfTheWeek.Sunday; default: throw new ArgumentException("无效的数字。请提供1到7之间的数字。"); } } /// <summary> /// 限定每月只能在1-28号之间执行任务 /// </summary> /// <param name="num"></param> /// <returns></returns> static int GetDaysOfMonth(int num) { if (num < 1 || num > 28) { throw new ArgumentException("无效的数字。请提供1到28之间的数字。"); } return num; }
Main
static void Main(string[] args) { TaskSchedulerConfig taskSchedulerConfig; try { var taskSchedulerConfigJson = args[0]; taskSchedulerConfig = JsonConvert.DeserializeObject<TaskSchedulerConfig>(taskSchedulerConfigJson); } catch { string demo = @"{ ""ApplicationPath"": ""C:\\YourApplication\\YourExecutable.exe"", ""TaskName"": ""DailyTask"", ""TaskDescription"": ""This is a daily task"", ""TaskExecutionCycle"": 0, ""StartBoundary"": ""2024/02/28 08:00:00"", ""DaysOfMonth"": 28, ""DaysOfWeek"": 3 }"; Console.WriteLine($"参数错误,正确示例:{demo}"); return; } try { using (TaskService taskService = new TaskService()) { // 创建一个新任务 TaskDefinition taskDefinition = taskService.NewTask(); taskDefinition.Principal.UserId = "SYSTEM"; // 设置为SYSTEM以在系统级别运行 // 设置任务的基本信息 taskDefinition.RegistrationInfo.Description = taskSchedulerConfig.TaskDescription; switch (taskSchedulerConfig.TaskExecutionCycle) { case 0: DailyTrigger dailyTrigger = new DailyTrigger(); dailyTrigger.StartBoundary = taskSchedulerConfig.StartBoundary; dailyTrigger.DaysInterval = 1; // 每天执行 taskDefinition.Triggers.Add(dailyTrigger); break; case 1: WeeklyTrigger weeklyTrigger = new WeeklyTrigger(); weeklyTrigger.StartBoundary = taskSchedulerConfig.StartBoundary; weeklyTrigger.DaysOfWeek = GetDaysOfTheWeek(taskSchedulerConfig.DaysOfWeek); weeklyTrigger.WeeksInterval = 1; // 每隔1周执行 taskDefinition.Triggers.Add(weeklyTrigger); break; case 2: MonthlyTrigger monthlyTrigger = new MonthlyTrigger(); monthlyTrigger.StartBoundary = taskSchedulerConfig.StartBoundary; monthlyTrigger.DaysOfMonth = new[] { GetDaysOfMonth(taskSchedulerConfig.DaysOfMonth) }; monthlyTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; // 每个月执行 taskDefinition.Triggers.Add(monthlyTrigger); break; default: Console.WriteLine("任务执行周期参数错误!正确示例:0 每日执行 1 每周执行 2 每月执行"); break; } // 设置要执行的程序路径 taskDefinition.Actions.Add(new ExecAction(taskSchedulerConfig.ApplicationPath, null, null)); // 将任务注册到 Windows 任务计划程序 taskService.RootFolder.RegisterTaskDefinition(taskSchedulerConfig.TaskName, taskDefinition); Console.WriteLine("任务计划创建成功!"); } } catch (Exception ex) { Console.WriteLine($"创建{taskSchedulerConfig.TaskName} 任务错误,错误原因是:{ex.Message}"); } }
到此这篇关于C#实现定时任务Task Scheduler的示例代码的文章就介绍到这了,更多相关C#定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!