Added scheduler and added more graceful error handling

This commit is contained in:
2026-04-14 18:26:09 +05:00
parent 3aa8b85c59
commit 5329b69c2e
5 changed files with 124 additions and 17 deletions
+59
View File
@@ -0,0 +1,59 @@
using System.Reflection;
using System.Text;
using Microsoft.Win32.TaskScheduler;
if(args.Length != 1)
{
Console.WriteLine("Usage: Scheduler <timeslot>");
return;
}
var timeslot = args[0];
if (!TimeSpan.TryParse(timeslot, out var _))
{
Console.WriteLine("Invalid timeslot format. Use HH:mm");
return;
}
var dir = new DirectoryInfo(File.ReadAllText("AppSettings.txt"))!;
var builder = new StringBuilder();
builder.AppendLine($"cd {dir.Parent!.FullName}");
builder.AppendLine($"dotnet run -- {timeslot}");
File.WriteAllText("run.bat", builder.ToString());
using (TaskService taskService = new TaskService())
{
try
{
var existingTask = taskService.GetTask("BadmintonBooker");
if (existingTask != null)
{
taskService.RootFolder.DeleteTask("BadmintonBooker", false);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting existing task: {ex.Message}");
}
TaskDefinition taskDef = taskService.NewTask();
taskDef.RegistrationInfo.Description = "Scheduled Task with Credentials";
taskDef.Principal.RunLevel = TaskRunLevel.Highest;
taskDef.Triggers.Add(new TimeTrigger
{
StartBoundary = DateTime.Today.AddDays(1) + TimeSpan.Parse("07:40")
});
taskDef.Actions.Add(new ExecAction("cmd", $"/c \"{Path.Combine(dir.FullName, "run.bat")}\" > C:\\Output.log 2>&1"));
var pass = File.ReadAllText("Password.txt");
taskService.RootFolder.RegisterTaskDefinition(
"BadmintonBooker",
taskDef,
TaskCreation.CreateOrUpdate,
"Shaamil",
pass,
TaskLogonType.Password
);
}