Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
Scheduled Task
Purpose
Create, modify, and review GrandNode scheduled tasks including the task class, DI registration, database seed, distributed-lock behavior, error handling, and task migrations.
When To Use
Use this skill when adding a new background task, changing an existing task's logic or interval, migrating a task name or seed entry for existing installations, or reviewing scheduled task correctness, idempotency, and multi-instance safety.
When Not To Use
Do not use this skill for message template content or email sending logic; combine with message-notification when a task sends emails.
Do not use this skill as the primary review for MongoDB query safety or security; combine with the relevant skill when those concerns apply.
Inputs Required
- Repository root.
- Task purpose and trigger description.
- Required time interval (minutes).
- Whether the task should be enabled by default.
- Domain entities the task reads or writes.
- Whether the task must respect per-store or per-language context.
Instructions
Mandatory Rules
Task Class
- Implement
IScheduleTaskfromGrand.Business.Core.Interfaces.System.ScheduleTaskswith a singleTask Execute()method. - Place the task class in
src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/. - Resolve all dependencies through constructor injection.
Execute()takes no parameters and receives noCancellationTokenfrom the caller. - Keep
Execute()idempotent: running it twice in a row must not corrupt data or duplicate side effects. - For tasks that process a collection of items, wrap each item in its own
try-catchblock. Log the error and continue with the next item; do not let a single-item failure abort the whole run. - Never call
Thread.Sleep,Task.Delay, or any other wait insideExecute(). The runner controls the interval.
DI Registration
- Register the task in
src/Modules/Grand.Module.ScheduledTasks/Startup/StartupApplication.csusing exactly:serviceCollection.AddKeyedScoped<IScheduleTask, YourTask>("Task name string"); - The service key string must exactly match the
ScheduleTaskNamestored in the database. Any mismatch means the runner cannot resolve the task.
Database Seed
- Add a
ScheduleTaskentry insrc/Modules/Grand.Module.Installer/Services/InstallDataScheduleTasks.csinsideInstallScheduleTasks():new ScheduleTask { ScheduleTaskName = "Task name string", // must equal the DI key Enabled = false, // prefer disabled by default StopOnError = false, TimeInterval = N // minutes } - Prefer
Enabled = falsefor new tasks so the administrator explicitly activates them. Only setEnabled = truefor tasks that must run immediately after installation (e.g.,"Send emails"). - Leave
StopOnError = falseunless the task manages a resource that is unsafe to run after a partial failure.
Existing Installations — Migrations
- Add a migration under
src/Modules/Grand.Module.Migration/Migrations/when changing theScheduleTaskName, defaultTimeInterval, orEnabledvalue for a task that already exists in production. Follow theIMigrationinterface and existing migration class patterns. - In a migration that adds a new task, insert the new
ScheduleTaskonly when it does not already exist (check byScheduleTaskNamebefore inserting). - In a migration that removes a task, delete by
ScheduleTaskNameand remove the DI registration.
Error Handling
- The runner sets
task.Enabled = falsewhenStopOnError = trueandExecute()throws an uncaught exception. Tasks withStopOnError = falseremain enabled and retry on the next interval. - Log unexpected exceptions with
ILogger<T>. Do not swallow them silently — the runner also logs at error level, but task-level context is valuable. - For partial-failure loops, update the item's state inside a
finallyblock so the next run does not re-process an item that was already attempted.
Multi-Instance Safety
- The runner uses
TryClaimTaskRun()— an atomic compare-and-set onLastStartUtc— to ensure only one instance executes a given task per interval window. Task classes do not need to implement their own locking. - Do not cache expensive results across
Execute()calls using instance fields. The task is registered asAddKeyedScoped, so a new instance is created for each execution.
Store and Language Context
- When a task must operate per store, inject
IStoreServiceand iterate overGetAllStores(). TheScheduleTask.StoreIdfield is available if the task should be restricted to a single store. - When locale-sensitive output is required, inject
ILanguageServiceand iterate over languages for the relevant store.
Recommendations
- Prefer reading a bounded batch of records (e.g., top 500) rather than loading an unbounded collection in one query.
- Prefer a short
TimeIntervalfor operational tasks (email sending = 1 min) and a long interval for maintenance tasks (sitemap generation = 10080 min = 7 days). - Prefer injecting
ILogger<T>for all non-trivial tasks to support observability. - Prefer structured log messages that include the task name and record ID when processing per-item.
Constraints
- Never place task classes outside
src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/. - Never register a task with a DI key that differs from its
ScheduleTaskNamein the database. - Never add a seed entry without also adding a DI registration, and vice versa.
- Never introduce locking, semaphores, or static shared state inside a task class.
- Never call
IEmailSenderdirectly from a task; useIMessageProviderServiceor queue viaIQueuedEmailServicefollowing the message-notification pattern.
Key Contracts
IScheduleTask (src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTask.cs)
public interface IScheduleTask
{
Task Execute();
}
ScheduleTask entity (src/Core/Grand.Domain/Tasks/ScheduleTask.cs)
public class ScheduleTask : BaseEntity
{
public string ScheduleTaskName { get; set; } // DI key and display name
public bool Enabled { get; set; }
public bool StopOnError { get; set; }
public int TimeInterval { get; set; } // minutes
public string StoreId { get; set; } // empty = all stores
public DateTime? LastStartUtc { get; set; }
public DateTime? LastSuccessUtc { get; set; }
public DateTime? LastNonSuccessEndUtc { get; set; }
public string LeasedByInstance { get; set; } // multi-instance lock holder
}
File Locations
| Concern | Path |
|---|---|
| IScheduleTask interface | src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTask.cs |
| Task classes | src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/ |
| DI registration | src/Modules/Grand.Module.ScheduledTasks/Startup/StartupApplication.cs |
| ScheduleTask entity | src/Core/Grand.Domain/Tasks/ScheduleTask.cs |
| Installer seed | src/Modules/Grand.Module.Installer/Services/InstallDataScheduleTasks.cs |
| Task runner (BackgroundService) | src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs |
| Task handler startup | src/Web/Grand.Web.Common/Startup/TaskHandler.cs |
| IScheduleTaskService | src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs |
| Migration example | src/Modules/Grand.Module.Migration/Migrations/2.1/MigrationScheduleTasks.cs |
| Tests — ScheduleTaskService | src/Tests/Grand.Modules.Tests/Services/BackgroundService/ScheduleTaskServiceTests.cs |
| Tests — BackgroundServiceTask | src/Tests/Grand.Web.Common.Tests/Infrastructure/BackgroundServiceTaskTests.cs |
Existing Task Inventory
| Class | DI key / ScheduleTaskName | Default interval | Default enabled |
|---|---|---|---|
QueuedMessagesSendScheduleTask |
"Send emails" |
1 min | true |
DeleteGuestsScheduleTask |
"Delete guests" |
1440 min | true |
UpdateExchangeRateScheduleTask |
"Update currency exchange rates" |
1440 min | true |
ClearCacheScheduleTask |
"Clear cache" |
120 min | false |
GenerateSitemapXmlTask |
"Generate sitemap XML file" |
10080 min | false |
EndAuctionsTask |
"End of the auctions" |
60 min | false |
CancelOrderScheduledTask |
"Cancel unpaid and pending orders" |
1440 min | false |
Expected Output
Produce one of these results:
- A new task class, DI registration, installer seed, and (when needed) migration.
- An updated task class with matching DI key, seed, and migration for existing installations.
- A review report listing task correctness, idempotency, or registration issues.
Include changed files, DI key, seed values, migration status, and remaining risks.
Validation Checklist
- Task class implements
IScheduleTaskand lives inBackgroundServices/. -
Execute()is idempotent and does not depend on execution order. - Per-item loops use individual
try-catchblocks. - DI key in
AddKeyedScopedexactly matches theScheduleTaskNameseed value. - Installer seed entry added with appropriate
EnabledandTimeInterval. - Migration added for tasks that affect existing installations.
- No static shared state or cross-call caching inside the task class.
-
ILogger<T>used for error and diagnostic output. - Tests cover
Execute()happy path and error-per-item behavior where applicable.
Examples
Example 1: Simple Maintenance Task
Input: Add a task that deletes expired product reservations every 60 minutes.
Output:
- Create
DeleteExpiredReservationsTask : IScheduleTaskinBackgroundServices/. - Inject
IProductReservationServiceandILogger<DeleteExpiredReservationsTask>. - In
Execute(): query expired reservations, delete each inside atry-catch, log errors and continue. - Register:
AddKeyedScoped<IScheduleTask, DeleteExpiredReservationsTask>("Delete expired reservations"). - Seed:
new ScheduleTask { ScheduleTaskName = "Delete expired reservations", Enabled = false, StopOnError = false, TimeInterval = 60 }.
Example 2: Per-Store Task
Input: Add a task that recalculates price tiers per store daily.
Output:
- Create
RecalculatePriceTiersTask : IScheduleTask. - Inject
IStoreServiceandIPricingService. - In
Execute(): call_storeService.GetAllStores(), loop each store, call_pricingService.RecalculateTiers(store.Id)wrapped in per-storetry-catch. - Register and seed with
TimeInterval = 1440.
Example 3: Renaming a Task in Migration
Input: The task "Recalculate price tiers" needs to be renamed to "Recalculate product pricing".
Output:
- Update the DI key in
StartupApplication.csto"Recalculate product pricing". - Add a migration class implementing
IMigrationthat finds theScheduleTaskby the oldScheduleTaskNameand updates it to the new name. - If no existing task is found, insert a new seed entry so the task exists on installations that never had the old name.