Schedules
Tips
Are you looking for the list of schedules defined by confinity? Check Confinity Schedules.
Allows you to execute code at a specific time and/or interval.
You need two things in order for a schedule to work.
- A class implementing the interface
IScheduledTask. - A module to configure your schedule.
Implementing a schedule
A schedule must implement the interface IScheduledTask. Apart from that, a few things work differently than most are used to.
- The current user is not available. In fact, each schedule runs under a different user.
- When ILogger<> is used, "LogError" and "LogCritical" are stored in the database for further analysis and error handling.
- Dependency Injection works as usual. Each schedule gets its own scope for execution.
Example:
public class DemoSchedule(IConfinityDbContextFactory dbContextFactory) : IScheduledTask
{
public Task Process(CancellationToken cancellationToken)
{
using var dbContext = dbContextFactory.CreateDbContext();
// ... do cool stuff
return Task.CompletedTask;
}
}
Initial configuration
A schedule must be configured in the AddModule method from IModuleConfiguration. The configuration should be straight forward. A few things to mention:
- enabled: true => Executes the schedule when times come. If you develop a module for multiple applications, make sure this does not cause problems.
- The next execution is calculated from the start. If you want to execute a schedule at a given time, say at 12 o clock, we have to specify the time.
Example configuration:
public class ScheduleDemoModule : IModuleConfiguration
{
public string ModuleKey { get; } = "schedule-demo";
public void AddModule(IModuleContext module)
{
module.Configure.RegisterScheduledTask<DemoSchedule>("Demo Schedule",
new DateTimeOffset(2020, 1, 1, 9, 0, 0, TimeSpan.Zero),
TimeSpan.FromHours(1));
}
The configuration is only evaluated if the schedule does not exist. The schedule configuration is automatically stored in the database and can be modified at runtime, as explained in the next chapter.
Configuring schedules at runtime
Users with the appropriate authorization can add, update and delete schedule configurations. This is needed, for example, to adjust the time of execution, disable a schedule or chose the stage a schedule should run on.
Delete is primarily useful for manually created configurations because automatically created ones will be recreated duringthe next startup if they don't exist.