123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using Microsoft.Win32.TaskScheduler;
- using System;
- using System.IO;
- using Task = Microsoft.Win32.TaskScheduler.Task;
- namespace Vinno.FIS.Sonopost.Upgrade
- {
- internal class TaskSchedulerHelper
- {
- private static readonly string _keeperFilePath = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 1)).FullName, "Vinno.FIS.Sonopost.Keeper.exe");
- private static readonly string _taskName = "SonopostProtectionTask";
- /// <summary>
- /// 安装计划任务
- /// </summary>
- public static void Install()
- {
- if (IsTaskExist(_taskName))
- {
- UnInstall();
- }
- InstallTask();
- }
- /// <summary>
- /// 卸载计划任务
- /// </summary>
- public static void UnInstall()
- {
- if (IsTaskExist(_taskName))
- {
- UninstallTask();
- }
- }
- private static bool IsTaskExist(string serviceName)
- {
- using (TaskService ts = new TaskService())
- {
- // 查询指定任务
- Task task = ts.GetTask(_taskName);
- if (task != null)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- private static void InstallTask()
- {
- using (TaskService ts = new TaskService())
- {
- // 创建新任务
- TaskDefinition td = ts.NewTask();
- td.RegistrationInfo.Description = "Sonopost Protection Task";
- // 设置触发器(每次系统启动时)会使钩子失效
- //BootTrigger bootTrigger = new BootTrigger();
- //td.Triggers.Add(bootTrigger);
- // 设置触发器: 任务注册时立即执行
- RegistrationTrigger registrationTrigger = new RegistrationTrigger();
- registrationTrigger.StartBoundary = DateTime.Now;
- td.Triggers.Add(registrationTrigger);
- LogonTrigger logonTrigger = new LogonTrigger();
- td.Triggers.Add(logonTrigger);
- //TimeTrigger hourlyTrigger = new TimeTrigger { Repetition = new RepetitionPattern(TimeSpan.FromHours(1), TimeSpan.Zero) };
- //td.Triggers.Add(hourlyTrigger);
- td.Principal.RunLevel = TaskRunLevel.Highest;
- td.Principal.LogonType = TaskLogonType.InteractiveToken;
- td.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
- td.Settings.DisallowStartIfOnBatteries = false;
- td.Settings.StopIfGoingOnBatteries = false;
- td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
- td.Settings.Compatibility = TaskCompatibility.V2_3;//Windows10配置
- // 设置要执行的操作
- td.Actions.Add(new ExecAction(_keeperFilePath, null, null));
- // 注册任务
- ts.RootFolder.RegisterTaskDefinition(_taskName, td, TaskCreation.CreateOrUpdate, @"Sonopost\VinnoUser", "VinnoTech", TaskLogonType.InteractiveToken);
- }
- }
- private static void UninstallTask()
- {
- using (TaskService ts = new TaskService())
- {
- // 检查任务是否存在并删除
- if (ts.GetTask(_taskName) != null)
- {
- ts.RootFolder.DeleteTask(_taskName);
- }
- }
- }
- }
- }
|