TaskSchedulerHelper.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Diagnostics;
  2. namespace DRG.DRGInterfaceClient
  3. {
  4. /// <summary>基于 schtasks 的 Windows 任务计划注册/注销(daily/weekly 外部定时用)。</summary>
  5. internal static class TaskSchedulerHelper
  6. {
  7. public static void Register(string taskName, string exePath, string frequency, string scheduledTime)
  8. {
  9. string sc = frequency == "weekly" ? "WEEKLY /D MON" : "DAILY";
  10. string st = "/ST " + (string.IsNullOrWhiteSpace(scheduledTime) ? "02:00" : scheduledTime.Trim());
  11. // /TR 的值为 "<exe>" --sync;整段用引号包裹,路径含空格也安全
  12. string tr = "/TR \"" + exePath + " --sync\"";
  13. string args = string.Format("/Create /F /TN \"{0}\" /SC {1} {2} {3}", taskName, sc, st, tr);
  14. RunSchtasks(args);
  15. }
  16. public static void Delete(string taskName)
  17. {
  18. RunSchtasks(string.Format("/Delete /TN \"{0}\" /F", taskName));
  19. }
  20. private static void RunSchtasks(string args)
  21. {
  22. try
  23. {
  24. var psi = new ProcessStartInfo("schtasks", args)
  25. {
  26. UseShellExecute = false,
  27. CreateNoWindow = true,
  28. RedirectStandardOutput = true
  29. };
  30. using (var p = Process.Start(psi))
  31. {
  32. string outp = p.StandardOutput.ReadToEnd();
  33. p.WaitForExit();
  34. Logger.Info(string.Format("schtasks {0} => exit {1} {2}",
  35. args, p.ExitCode, outp));
  36. }
  37. }
  38. catch (System.Exception ex)
  39. {
  40. Logger.Error("执行 schtasks 失败", ex);
  41. }
  42. }
  43. }
  44. }