一、概述
Windows电脑提供了任务计划程序,对于需要定时执行的任务,可以利用任务计划程序来协助执行。在任务计划程序的帮助下,可以创建要由Windows运行的各种自动化任务。计划任务具体的特性和属性可以参考官网。另外在Linux和Unix系统中也有类似的工具Corn。
二、手动创建任务计划程序
1、启动任务计划服务
- 方式一:开始菜单->运行,输入services.msc 打开服务窗口,亦可以通过控制面板->管理工具->服务,手动对Task Scheduler服务进行启动。
- 方式二:通过命令形式启用服务
2、停止任务计划程序服务
- 方式一:打开服务窗口,右键关闭服务
- 方式二:通过命令方式
3、查看Task Scheduler状态
4、打开任务计划程序
- 方式一:控制面板-管理工具-任务计划程序
- 方式二:windows + R键,打开运行,并输入“taskschd.msc”
5、创建任务计划程序
- 在管理界面,点击任务计划程序库,如图:
三、代码创建任务计划程序
1、将基本操作封装为公共库
using System; using Microsoft.Win32.TaskScheduler; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Linq; namespace SchedulerTask { /// <summary> /// windows系统里面的计划任务 /// </summary> public class SchedulerTaskBus { /// <summary> /// 创建一个以指定日期时间为触发条件 /// </summary> /// <param name="taskName">任务名称</param> /// <param name="taskDescription">任务描述</param> /// <param name="startBoundary">指定日期时间</param> /// <param name="path">应用程序路径</param> /// <param name="arguments">应用程序参数</param> /// <param name="subFolderName">文件夹名称</param> public static void CreateOnceRunTask(string subFolderName, string taskName, string taskDescription, string path, DateTime startBoundary, string arguments) { using (TimeTrigger trigger = new TimeTrigger(startBoundary)) { using (ExecAction action = new ExecAction(path, arguments, null)) { CreateTask(subFolderName, taskName, taskDescription, trigger, action); } } } /// <summary> /// 创建一个计划任务 /// </summary> /// <param name="taskName">任务名称</param> /// <param name="taskDescription">任务描述</param> /// <param name="trigger">触发条件</param> /// <param name="action">执行任务</param> /// <param name="subFolderName">文件夹名称</param> public static void CreateTask(string subFolderName, string taskName, string taskDescription, Trigger trigger, Microsoft.Win32.TaskScheduler.Action action) { using (TaskService ts = new TaskService()) { using (TaskDefinition td = ts.NewTask()) { td.RegistrationInfo.Description = taskDescription; //http://stackoverflow.com/questions/8170236/how-to-set-run-only-if-logged-in-and-run-as-with-taskscheduler-in-c //td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //td.Principal.LogonType = TaskLogonType.InteractiveToken; td.Principal.RunLevel = TaskRunLevel.Highest; td.Triggers.Add(trigger); td.Actions.Add(action); TaskFolder folder = ts.RootFolder; if (!string.IsNullOrWhiteSpace(subFolderName)) { if (!folder.SubFolders.Exists(subFolderName)) { folder = folder.CreateFolder(subFolderName); } else { folder = folder.SubFolders[subFolderName]; } } folder.RegisterTaskDefinition(taskName, td); folder.Dispose(); folder = null; } } } /// <summary> /// 删除某一个子文件夹 /// </summary> /// <param name="folderName">绝对路径</param> public static void DeleteSubFolders(string folderName = @"Test") { // Get the service on the local machine using (TaskService taskService = new TaskService()) { using (TaskFolder folder = taskService.GetFolder(folderName)) { if (folder.Tasks.Count > 0) { throw new InvalidOperationException("TASKS_EXIST"); } if (folder.SubFolders.Count > 0) { throw new InvalidOperationException("SUB_FOLDERS_EXIST"); } using (TaskFolder folderParent = taskService.GetFolder(folder.Path.Replace(@"" + folder.Name, ""))) { folderParent.DeleteFolder(folder.Name); } } } } /// <summary> /// 获取某一个文件夹下面的所有子文件夹 /// </summary> /// <param name="folderName">传null表示根文件夹</param> /// <returns></returns> public static IEnumerable<TaskFolder> GetAllSubFolder(string folderName = @"Test") { using (TaskService taskService = new TaskService()) { TaskFolder folder = taskService.RootFolder; if (!string.IsNullOrWhiteSpace(folderName)) { folder = taskService.GetFolder(folderName); } foreach (TaskFolder subFolder in folder.SubFolders) { yield return subFolder; } } } /// <summary> /// 删除某一个文件夹下面的某一个任务 /// </summary> /// <param name="taskName">要删除的任务名称</param> /// <param name="folderName">传null表示根文件夹</param> public static void DeleteTask(string folderName, string taskName) { using (TaskService taskService = new TaskService()) { TaskFolder folder = taskService.RootFolder; // 判断文件夹和任务是否存在 if (folder.SubFolders.Exists(folderName) && folder.SubFolders[folderName].Tasks.Exists(taskName)) { folder.SubFolders[folderName].DeleteTask(taskName); } folder.Dispose(); folder = null; } } /// <summary> /// 获取所有任务 /// </summary> /// <returns></returns> public static IEnumerable<Task> GetAllTask() { using (TaskService taskService = new TaskService()) { return taskService.AllTasks; } } /// <summary> /// 获取某一个文件夹下面的所有任务 /// </summary> /// <param name="folderName">传null表示根文件夹</param> /// <returns></returns> public static List<Task> GetAllTask(string folderName = @"Test") { using (TaskService taskService = new TaskService()) { TaskFolder folder = taskService.RootFolder; if (!string.IsNullOrWhiteSpace(folderName) && folder.SubFolders.Exists(folderName)) { folder = taskService.GetFolder(folderName); return folder.AllTasks.ToList(); } return new List<Task>(0); } } /// <summary> /// 查找符合条件的所有Task /// </summary> /// <param name="regex"></param> /// <param name="searchAllFolders"></param> /// <returns></returns> public static IEnumerable<Task> GetAllTask(Regex regex, bool searchAllFolders = true) { using (TaskService taskService = new TaskService()) { return taskService.FindAllTasks(regex, searchAllFolders); } } /// <summary> /// 查找符合条件的Task /// </summary> /// <param name="taskName"></param> /// <param name="searchAllFolders"></param> /// <returns></returns> public static Task GetTask(string taskName, bool searchAllFolders = true) { using (TaskService taskService = new TaskService()) { return taskService.FindTask(taskName, searchAllFolders); } } public static bool IsExist(string folderName,string taskName) { using (TaskService taskService = new TaskService()) { TaskFolder folder = taskService.RootFolder; // 判断文件夹和任务是否存在 return folder.SubFolders.Exists(folderName) && folder.SubFolders[folderName].Tasks.Exists(taskName); } } } }
2、调用公共库
string taskName = $"测试"; string taskDescription = $"测试计划任务"; string arguments = $"arg1={xx}&arg2={xx}";
SchedulerTaskBus.CreateOnceRunTask("Test", taskName, taskDescription, $"{appName}.exe", DateTime.Now.AddDays(1), arguments);