分享一个我自己写的 Windows 定时任务计划(Task Scheduler) 动态创建代码,没做太多封装,留个实现笔记

首先封装一个简单配置项的类


1 public classTaskSchedulerConfig2 {3     /// <summary>
4     ///引用程序路径5     /// </summary>
6     public string ApplicationPath { get; set; }7     /// <summary>
8     ///引用程序参数9     /// </summary>
10     //public string ApplicationParameter { get; set; }
11     /// <summary>
12     ///任务名称13     /// </summary>
14     public string TaskName { get; set; }15     /// <summary>
16     ///任务说明17     /// </summary>
18     public string TaskDescription { get; set; }19     /// <summary>
20     ///任务执行周期 0 每日执行 1 每周执行 2 每月执行21     /// </summary>
22     public int TaskExecutionCycle { get; set; }23     /// <summary>
24     ///开始执行时间范围 yyyy/MM/dd HH:mm:ss25     /// </summary>
26     public DateTime StartBoundary { get; set; }27     /// <summary>
28     ///每月的第几号执行29     /// </summary>
30     public int DaysOfMonth { get; set; }31     /// <summary>
32     ///每周的周几执行33     /// </summary>
34     public int DaysOfWeek { get; set; }35 
36 
37 }

View Code


1 /// <summary>
2         ///根据数字1-7来设置周一 - 周日3         /// </summary>
4         /// <param name="num"></param>
5         /// <returns></returns>
6         static DaysOfTheWeek GetDaysOfTheWeek(intnum)7 {8             switch(num)9 {10                 case 1:11                     returnDaysOfTheWeek.Monday;12                 case 2:13                     returnDaysOfTheWeek.Tuesday;14                 case 3:15                     returnDaysOfTheWeek.Wednesday;16                 case 4:17                     returnDaysOfTheWeek.Thursday;18                 case 5:19                     returnDaysOfTheWeek.Friday;20                 case 6:21                     returnDaysOfTheWeek.Saturday;22                 case 7:23                     returnDaysOfTheWeek.Sunday;24                 default:25                     throw new ArgumentException("无效的数字。请提供1到7之间的数字。");26 }27 }28         /// <summary>
29         ///限定每月只能在1-28号之间执行任务30         /// </summary>
31         /// <param name="num"></param>
32         /// <returns></returns>
33         static int GetDaysOfMonth(intnum)34 {35             if (num < 1 || num > 28)36 {37                 throw new ArgumentException("无效的数字。请提供1到28之间的数字。");38 }39             returnnum;40         }

两个范围判定的方法


1 static void Main(string[] args)2 {3 
4 TaskSchedulerConfig taskSchedulerConfig;5             try
6 {7                 var taskSchedulerConfigJson = args[0];8                 taskSchedulerConfig = JsonConvert.DeserializeObject<TaskSchedulerConfig>(taskSchedulerConfigJson);9 }10             catch
11 {12                 string demo = @"{13 ""ApplicationPath"": ""C:\\YourApplication\\YourExecutable.exe"",14 ""TaskName"": ""DailyTask"",15 ""TaskDescription"": ""This is a daily task"",16 ""TaskExecutionCycle"": 0,17 ""StartBoundary"": ""2024/02/28 08:00:00"",18 ""DaysOfMonth"": 28,19 ""DaysOfWeek"": 320 }";21 
22                 Console.WriteLine($"参数错误,正确示例:{demo}");23                 return;24 }25 
26 
27             try
28 {29                 using (TaskService taskService = newTaskService())30 {31                     //创建一个新任务
32                     TaskDefinition taskDefinition =taskService.NewTask();33                     taskDefinition.Principal.UserId = "SYSTEM"; //设置为SYSTEM以在系统级别运行34                     //设置任务的基本信息
35                     taskDefinition.RegistrationInfo.Description =taskSchedulerConfig.TaskDescription;36 
37                     switch(taskSchedulerConfig.TaskExecutionCycle)38 {39                         case 0:40                             DailyTrigger dailyTrigger = newDailyTrigger();41                             dailyTrigger.StartBoundary =taskSchedulerConfig.StartBoundary;42                             dailyTrigger.DaysInterval = 1; //每天执行
43 taskDefinition.Triggers.Add(dailyTrigger);44                             break;45                         case 1:46                             WeeklyTrigger weeklyTrigger = newWeeklyTrigger();47                             weeklyTrigger.StartBoundary =taskSchedulerConfig.StartBoundary;48                             weeklyTrigger.DaysOfWeek =GetDaysOfTheWeek(taskSchedulerConfig.DaysOfWeek);49                             weeklyTrigger.WeeksInterval = 1; //每隔1周执行
50 taskDefinition.Triggers.Add(weeklyTrigger);51                             break;52                         case 2:53                             MonthlyTrigger monthlyTrigger = newMonthlyTrigger();54                             monthlyTrigger.StartBoundary =taskSchedulerConfig.StartBoundary;55                             monthlyTrigger.DaysOfMonth = new[] { GetDaysOfMonth(taskSchedulerConfig.DaysOfMonth) };56                             monthlyTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; //每个月执行
57 taskDefinition.Triggers.Add(monthlyTrigger);58                             break;59                         default:60                             Console.WriteLine("任务执行周期参数错误!正确示例:0 每日执行 1 每周执行 2 每月执行");61                             break;62 }63 
64 
65 
66                     //设置要执行的程序路径
67                     taskDefinition.Actions.Add(new ExecAction(taskSchedulerConfig.ApplicationPath, null, null));68 
69                     //将任务注册到 Windows 任务计划程序
70 taskService.RootFolder.RegisterTaskDefinition(taskSchedulerConfig.TaskName, taskDefinition);71                     Console.WriteLine("任务计划创建成功!");72 }73 }74             catch(Exception ex)75 {76                 Console.WriteLine($"创建{taskSchedulerConfig.TaskName} 任务错误,错误原因是:{ex.Message}");77 }78 
79            
80         }

Main

标签: none

添加新评论