- 1 year ago
The ConnectionString property has not been initialized. Schedule task on windows
To schedule a task in Windows using C#, you can make use of the TaskScheduler
class from the Microsoft.Win32.TaskScheduler
namespace. Here's an example that demonstrates how to schedule a task:
csharpusing System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main()
{
// Create a new task
using (TaskService taskService = new TaskService())
{
// Define the task properties
TaskDefinition taskDefinition = taskService.NewTask();
taskDefinition.RegistrationInfo.Description = "My Scheduled Task";
// Set the task trigger
DailyTrigger trigger = new DailyTrigger();
trigger.StartBoundary = DateTime.Today.AddHours(8); // Set the start time
trigger.DaysInterval = 1; // Set the interval to daily
taskDefinition.Triggers.Add(trigger);
// Set the action to execute
taskDefinition.Actions.Add(new ExecAction("path_to_executable", "arguments", null));
// Register the task with the task scheduler
taskService.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition);
}
Console.WriteLine("Task scheduled successfully.");
}
}
In this example, the TaskScheduler
class is used to create a new task. The task properties, such as the description, trigger, and action, are defined and configured. Finally, the task is registered with the task scheduler using the RegisterTaskDefinition
method.
Make sure to replace "path_to_executable"
with the actual path to the executable file you want to run as the task, and "arguments"
with any command-line arguments if required. Also, set the desired task name and adjust the trigger settings according to your specific scheduling needs.
Please note that scheduling a task typically requires administrative privileges on the system, and you may need to run the application as an administrator to create the task successfully.