using System.Diagnostics;
namespace DRG.DRGInterfaceClient
{
/// 基于 schtasks 的 Windows 任务计划注册/注销(daily/weekly 外部定时用)。
internal static class TaskSchedulerHelper
{
public static void Register(string taskName, string exePath, string frequency, string scheduledTime)
{
string sc = frequency == "weekly" ? "WEEKLY /D MON" : "DAILY";
string st = "/ST " + (string.IsNullOrWhiteSpace(scheduledTime) ? "02:00" : scheduledTime.Trim());
// /TR 的值为 "" --sync;整段用引号包裹,路径含空格也安全
string tr = "/TR \"" + exePath + " --sync\"";
string args = string.Format("/Create /F /TN \"{0}\" /SC {1} {2} {3}", taskName, sc, st, tr);
RunSchtasks(args);
}
public static void Delete(string taskName)
{
RunSchtasks(string.Format("/Delete /TN \"{0}\" /F", taskName));
}
private static void RunSchtasks(string args)
{
try
{
var psi = new ProcessStartInfo("schtasks", args)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
using (var p = Process.Start(psi))
{
string outp = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Logger.Info(string.Format("schtasks {0} => exit {1} {2}",
args, p.ExitCode, outp));
}
}
catch (System.Exception ex)
{
Logger.Error("执行 schtasks 失败", ex);
}
}
}
}