Added scheduler and added more graceful error handling
This commit is contained in:
@@ -0,0 +1 @@
|
||||
C:\Users\Shaamil\Desktop\BadmintonBooker\Scheduler
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="AppSettings.txt" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TaskScheduler" Version="2.12.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in New Issue
Block a user