How to create Task Scheduler.
Step-by-step process.
what files should we create
Loading
How to create Task Scheduler.
Step-by-step process.
what files should we create
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 28, 2025, 1:24 PM EST
Hi Shubham,
Creating a Task Scheduler in Windows to run a .NET Core application involves several steps. Below is a step-by-step guide to help you set it up:
Step 1: Create a .NET Core Application
1. Install .NET Core SDK: Ensure you have the .NET Core SDK installed on your machine. You can download it from the [official .NET website](https://dotnet.microsoft.com/download).
2. Create a New .NET Core Project:
- Open a command prompt or terminal.
- Run the following command to create a new console application:
- Navigate to the project directory:
cd MyScheduledTask3. Build the Project:
- Run the following command to build the project:
4. Publish the Project:
- Publish the project to create a self-contained executable:
- The published files will be located in the `bin/Release/netX.X/win-x64/publish` directory (replace `netX.X` with the appropriate .NET Core version).
Step 2: Create a Batch File to Run the .NET Core Application
1. Create a Batch File:
- Create a new text file in the publish directory and name it `RunMyScheduledTask.bat`.
- Open the batch file in a text editor and add the following content:
@echo off cd /d "%~dp0" MyScheduledTask.exe- Save and close the file.
Step 3: Set Up Task Scheduler
1. Open Task Scheduler:
- Press `Win + R`, type `taskschd.msc`, and press Enter to open the Task Scheduler.
2. Create a New Task:
- In the Task Scheduler, click on "Create Task" in the right-hand pane.
3. General Tab:
- Enter a name for the task (e.g., "RunMyScheduledTask").
- Optionally, provide a description.
- Select "Run whether user is logged on or not" and check "Do not store password".
4. Triggers Tab:
- Click on "New..." to create a new trigger.
- Set the trigger to your desired schedule (e.g., daily, weekly, at startup, etc.).
- Configure the start date, time, and recurrence as needed.
- Click "OK" to save the trigger.
5. Actions Tab:
- Click on "New..." to create a new action.
- Set "Action" to "Start a program".
- In the "Program/script" field, browse to the `RunMyScheduledTask.bat` file you created earlier.
- In the "Start in" field, enter the path to the directory containing the batch file (e.g., `C:\path\to\publish\directory`).
- Click "OK" to save the action.
6. Conditions Tab:
- Configure any additional conditions if needed (e.g., start the task only if the computer is idle).
7. Settings Tab:
- Configure any additional settings if needed (e.g., allow the task to be run on demand, stop the task if it runs longer than a specified time, etc.).
8. Save the Task:
- Click "OK" to save the task.
Step 4: Test the Task
1. Run the Task Manually:
- In the Task Scheduler, find your task in the list, right-click it, and select "Run" to test it.
- Check the output or logs to ensure the task runs as expected.
2. Check for Errors:
- If the task does not run as expected, check the "Last Run Result" in the Task Scheduler and review any error messages.
Files to Create
- .NET Core Application:The main executable and associated DLLs.
- Batch File (`RunMyScheduledTask.bat`): A script to run the .NET Core application.
By following these steps, you can successfully create a Task Scheduler task to run your .NET Core application on a specified schedule.
Vinay SinghRank #604 · 4K reputationPosted Jan 28, 2025, 8:42 PM EST
Hi Subham,
Plesae refer the below link this may help you
https://www.c-sharpcorner.com/blogs/scheduling-in-asp-net-mvc-core
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 26, 2025, 5:32 AM EST
Part -1
Create these files in your .NET project:
Create these tables:
CREATE TABLE ScheduledTasks ( Id INT PRIMARY KEY IDENTITY(1,1), TaskName NVARCHAR(100) NOT NULL, TaskType NVARCHAR(50) NOT NULL, -- HTTP, SQL, EXE ScheduleCron NVARCHAR(50) NOT NULL, IsEnabled BIT NOT NULL DEFAULT 1, LastRunTime DATETIME, NextRunTime DATETIME, Configuration NVARCHAR(MAX) -- JSON config ); CREATE TABLE ExecutionHistory ( Id INT PRIMARY KEY IDENTITY(1,1), TaskId INT FOREIGN KEY REFERENCES ScheduledTasks(Id), StartTime DATETIME NOT NULL, EndTime DATETIME, Status NVARCHAR(20) NOT NULL, Output NVARCHAR(MAX) );Models/ScheduledTask.cs
public class ScheduledTask { public int Id { get; set; } public string TaskName { get; set; } public string TaskType { get; set; } public string ScheduleCron { get; set; } public bool IsEnabled { get; set; } public DateTime? LastRunTime { get; set; } public DateTime? NextRunTime { get; set; } public string Configuration { get; set; } // JSON config }Models/ExecutionHistory.cs
Services/DatabaseContext.cs
public class DatabaseContext : DbContext { public DatabaseContext(DbContextOptions options) : base(options) { } public DbSet ScheduledTasks { get; set; } public DbSet ExecutionHistory { get; set; } }Services/TaskSchedulerService.cs
public class TaskSchedulerService : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _services; private readonly PeriodicTimer _timer = new(TimeSpan.FromMinutes(1)); public TaskSchedulerService( ILogger logger, IServiceProvider services) { _logger = logger; _services = services; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (await _timer.WaitForNextTickAsync(stoppingToken)) { using var scope = _services.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); var taskRunner = scope.ServiceProvider.GetRequiredService(); var dueTasks = await dbContext.ScheduledTasks .Where(t => t.IsEnabled && t.NextRunTime <= DateTime.UtcNow) .ToListAsync(stoppingToken); foreach (var task in dueTasks) { _logger.LogInformation($"Executing task {task.TaskName}"); await taskRunner.ExecuteTaskAsync(task); } } } }Tuhin PaulRank #7 · 71.9K reputationPosted Feb 26, 2025, 5:41 AM EST
Part -2
Services/TaskRunnerService.cs
public class TaskRunnerService { private readonly DatabaseContext _dbContext; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; public TaskRunnerService( DatabaseContext dbContext, IHttpClientFactory httpClientFactory, ILogger logger) { _dbContext = dbContext; _httpClientFactory = httpClientFactory; _logger = logger; } public async Task ExecuteTaskAsync(ScheduledTask task) { var history = new ExecutionHistory { TaskId = task.Id, StartTime = DateTime.UtcNow, Status = "Running" }; try { await _dbContext.ExecutionHistory.AddAsync(history); await _dbContext.SaveChangesAsync(); switch (task.TaskType.ToUpper()) { case "HTTP": await ExecuteHttpTask(task); break; case "SQL": await ExecuteSqlTask(task); break; case "EXE": ExecuteExeTask(task); break; } history.Status = "Success"; history.EndTime = DateTime.UtcNow; } catch (Exception ex) { history.Status = "Failed"; history.Output = ex.ToString(); _logger.LogError(ex, $"Task {task.TaskName} failed"); } finally { task.LastRunTime = DateTime.UtcNow; task.NextRunTime = CalculateNextRun(task.ScheduleCron); await _dbContext.SaveChangesAsync(); } } private async Task ExecuteHttpTask(ScheduledTask task) { var config = JsonSerializer.Deserialize(task.Configuration); var client = _httpClientFactory.CreateClient(); var response = await client.SendAsync(new HttpRequestMessage( new HttpMethod(config.Method), config.Url )); response.EnsureSuccessStatusCode(); } private DateTime CalculateNextRun(string cronExpression) { var schedule = CronExpression.Parse(cronExpression); return schedule.GetNextOccurrence(DateTime.UtcNow) ?? DateTime.UtcNow.AddHours(1); } }Program.cs
var builder = Host.CreateApplicationBuilder(args); builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddHttpClient(); builder.Services.AddHostedService(); builder.Services.AddScoped(); var host = builder.Build(); host.Run();appsettings.json
{ "ConnectionStrings": { "DefaultConnection": "Server=.;Database=TaskScheduler;Trusted_Connection=True;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.Hosting.Lifetime": "Information" } } }Cron Schedule Support: Uses
Cronospackage for cron expressionsTask Types: Supports HTTP, SQL, and EXE tasks
Error Handling: Detailed execution history with error logs
Thread Safety: Proper scoping with DI containers
Configuration: JSON-based configuration for different task types
Install required packages:
Create database using EF Core migrations:
dotnet ef migrations add InitialCreate dotnet ef database updateCreate sample task:
var task = new ScheduledTask { TaskName = "Daily Cleanup", TaskType = "HTTP", ScheduleCron = "0 2 * * *", // Daily at 2 AM Configuration = JsonSerializer.Serialize(new HttpTaskConfig { Url = "https://api.example.com/cleanup", Method = "POST" }) };Tuhin PaulRank #7 · 71.9K reputationPosted Feb 26, 2025, 5:41 AM EST
Part -3
HLD overview:
Satya KarkiRank #78 · 24.6K reputationPosted Feb 26, 2025, 6:19 AM EST
Hi,
You can use hangfire or Quartz.NET for .NET application. You can follow the article: https://www.csharp.com/article/scheduling-background-jobs-in-asp-net-core-using-quartz-net/
Sandhiya PriyaRank #26 · 43.2K reputationPosted Jan 2, 2026, 6:36 AM EST
Below is a simple, step-by-step guide to create a Task Scheduler in C# (.NET).
This explains what to create, which files are needed, and how it works.
Decide the type of Task Scheduler
There are two common approaches:
Option A – Windows Task Scheduler (Recommended)
Runs even after reboot
No need to keep app running
Best for production
Option B – Custom Scheduler (Timer / BackgroundService)
Runs only while app is running
Good for web apps or services
I’ll explain both, starting with the recommended one.
OPTION A: Windows Task Scheduler (Step-by-Step)
Step 1: Create a Console Application
Create a Console App (.NET Framework or .NET Core).
Files created:
Step 2: Write the Task Logic
This is the code that runs on schedule.
Program.cs
class Program { static void Main() { // Your scheduled work File.AppendAllText( @"C:\Logs\TaskLog.txt", DateTime.Now + " - Task executed\n" ); } }Build the project ? generates
TaskJob.exeStep 3: Create Task in Windows Task Scheduler
Open Task Scheduler
Click Create Basic Task
Name ?
MyDailyJobTrigger ? Daily / Hourly / On startup
Action ? Start a program
Browse ? select
TaskJob.exeStart in ? folder path of EXE
Finish
Task will now run automatically.
Files Required (Option A)
OPTION B: Custom Task Scheduler in C# (Timer Based)
Step 1: Create Console / Web App
Files:
Step 2: Create Job File
Job.cs
public class Job { public static void Run() { Console.WriteLine("Task running at " + DateTime.Now); } }Step 3: Create Scheduler
Scheduler.cs
using System.Timers; public class Scheduler { private static Timer _timer; public static void Start() { _timer = new Timer(60000); // 1 minute _timer.Elapsed += (s, e) => Job.Run(); _timer.Start(); } }Step 4: Start Scheduler
Program.cs
class Program { static void Main() { Scheduler.Start(); Console.ReadLine(); // keep app alive } }Files Required (Option B)
App must be running for tasks to execute.
OPTION C: ASP.NET Core (Background Service)
Used in Web APIs.
Files:
Uses
BackgroundServiceorIHostedService.Which one should YOU use?
Summary (Quick Answer)
Best & safest ? Windows Task Scheduler
Create ? Console App (.exe)
Scheduler ? Windows Task Scheduler UI
Files needed ?
Program.cs?exe