Adds the scheduled job domain model

This commit is contained in:
BinaryAlley committed 2026-09-03 12:48:35 -07:00
1 parent 145fc77346
commit 7fbb4dc0d3
18 files changed
+796

No files matched your search

@@ -0,0 +1,17 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
/// <summary>
/// Enumeration for the types of schedules of scheduled jobs.
/// </summary>
public enum ScheduleType
{
/// <summary>
/// The scheduled job repeats with an interval measured in minutes.
/// </summary>
WithIntervalInMinutes,
/// <summary>
/// The scheduled job repeats daily at a fixed hour and minute.
/// </summary>
DailyAtHourAndMinute
}
@@ -0,0 +1,27 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
/// <summary>
/// Enumeration for the statuses of scheduled jobs.
/// </summary>
public enum ScheduledJobStatus
{
/// <summary>
/// The scheduled job was added, but its execution cycle was not started.
/// </summary>
Added,
/// <summary>
/// The execution cycle of the scheduled job is active, and the job is waiting for its next scheduled execution.
/// </summary>
Active,
/// <summary>
/// The task of the scheduled job is currently being executed.
/// </summary>
Running,
/// <summary>
/// The scheduled job finished its latest one time execution.
/// </summary>
Completed
}
@@ -0,0 +1,17 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
/// <summary>
/// Enumeration for the types of tasks a scheduled job can execute.
/// </summary>
public enum ScheduledTaskType
{
/// <summary>
/// The scheduled job scans all enabled media libraries.
/// </summary>
ScanMediaLibraries,
/// <summary>
/// The scheduled job cleans the temporary directory of the application.
/// </summary>
CleanTemporaryFiles
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Domain.Common.Errors;
/// <summary>
/// Scheduled job error types.
/// </summary>
public static partial class Errors
{
public static class Scheduling
{
public static Error ScheduledJobNameCannotBeEmpty => Error.Validation(description: nameof(ScheduledJobNameCannotBeEmpty));
public static Error IntervalMinutesMustBePositive => Error.Validation(description: nameof(IntervalMinutesMustBePositive));
public static Error HourMustBeBetweenZeroAndTwentyThree => Error.Validation(description: nameof(HourMustBeBetweenZeroAndTwentyThree));
public static Error MinuteMustBeBetweenZeroAndFiftyNine => Error.Validation(description: nameof(MinuteMustBeBetweenZeroAndFiftyNine));
public static Error ScheduledJobAlreadyExists => Error.Conflict(description: nameof(ScheduledJobAlreadyExists));
public static Error ScheduledJobNotFound => Error.NotFound(description: nameof(ScheduledJobNotFound));
public static Error ScheduledJobExecutionAlreadyExists => Error.Conflict(description: nameof(ScheduledJobExecutionAlreadyExists));
public static Error ScheduledJobExecutionNotFound => Error.NotFound(description: nameof(ScheduledJobExecutionNotFound));
public static Error ScheduledJobCycleAlreadyStarted => Error.Forbidden(description: nameof(ScheduledJobCycleAlreadyStarted));
public static Error ScheduledJobNotStarted => Error.Forbidden(description: nameof(ScheduledJobNotStarted));
public static Error ScheduledJobAlreadyRunning => Error.Forbidden(description: nameof(ScheduledJobAlreadyRunning));
public static Error CanOnlyCompleteRunningScheduledJob => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScheduledJob));
public static Error InvalidScheduleType => Error.Validation(description: nameof(InvalidScheduleType));
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
/// <summary>
/// Value object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class UserId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private UserId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId CreateUnique()
{
return new UserId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId Create(Guid value)
{
return new UserId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when a scheduled job is added.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job that was added.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobAddedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the execution cycle of a scheduled job is started.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle was started.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobCycleStartedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the execution cycle of a scheduled job is stopped.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle was stopped.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobCycleStoppedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the task of a scheduled job completes its execution.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task completed its execution.</param>
/// <param name="RunId">The unique identifier of the current execution of the task of the scheduled job.</param>
/// <param name="TaskType">The type of the task that completed its execution.</param>
/// <param name="IsCycleRun"><see langword="true"/> when the execution was triggered by the execution cycle of the scheduled job, <see langword="false"/> when it was a one time execution.</param>
/// <param name="CompletedOnUtc">The date and time when the execution completed.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}, RunId: {RunId}")]
public record ScheduledJobExecutionCompletedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
Guid RunId,
ScheduledTaskType TaskType,
bool IsCycleRun,
DateTime CompletedOnUtc
) : IDomainEvent
{
/// <summary>
/// Gets the date and time when the domain event occurred.
/// </summary>
public DateTime OccurredOnUtc => CompletedOnUtc;
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the task of a scheduled job starts its execution.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task started executing.</param>
/// <param name="RunId">The unique identifier of the current execution of the task of the scheduled job.</param>
/// <param name="TaskType">The type of the task that started executing.</param>
/// <param name="IsCycleRun"><see langword="true"/> when the execution was triggered by the execution cycle of the scheduled job, <see langword="false"/> when it was a one time execution.</param>
/// <param name="StartedOnUtc">The date and time when the execution started.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}, RunId: {RunId}")]
public record ScheduledJobExecutionStartedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
Guid RunId,
ScheduledTaskType TaskType,
bool IsCycleRun,
DateTime StartedOnUtc
) : IDomainEvent
{
/// <summary>
/// Gets the date and time when the domain event occurred.
/// </summary>
public DateTime OccurredOnUtc => StartedOnUtc;
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the execution of the task of a scheduled job is stopped while it is running.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose running execution was stopped.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobExecutionStoppedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when the task of a scheduled job is fired once.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task was fired.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobFiredDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Domain event raised when a scheduled job is removed.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job that was removed.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {ScheduledJobId.Value}")]
public record ScheduledJobRemovedDomainEvent(
Guid Id,
ScheduledJobId ScheduledJobId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,229 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
/// <summary>
/// Aggregate root for a scheduled job.
/// </summary>
[DebuggerDisplay("Id: {Id.Value}")]
public class ScheduledJob : AggregateRoot<ScheduledJobId>
{
private Optional<Guid> _currentExecutionRunId;
/// <summary>
/// Gets the name of the scheduled job.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the type of the task executed by the scheduled job.
/// </summary>
public ScheduledTaskType TaskType { get; private set; }
/// <summary>
/// Gets the schedule of the scheduled job.
/// </summary>
public Schedule Schedule { get; private set; }
/// <summary>
/// Gets the status of the scheduled job.
/// </summary>
public ScheduledJobStatus Status { get; private set; }
/// <summary>
/// Gets the object representing the unique identifier of the user that owns the scheduled job.
/// </summary>
public UserId OwnerUserId { get; private set; }
/// <summary>
/// Gets the optional date and time when the task of the scheduled job last started its execution.
/// </summary>
public Optional<DateTime> LastStartedOnUtc { get; private set; }
/// <summary>
/// Gets the optional date and time when the task of the scheduled job last completed its execution.
/// </summary>
public Optional<DateTime> LastCompletedOnUtc { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJob"/> class.
/// </summary>
/// <param name="id">The object representing the unique identifier of the scheduled job.</param>
/// <param name="name">The name of the scheduled job.</param>
/// <param name="taskType">The type of the task executed by the scheduled job.</param>
/// <param name="schedule">The schedule of the scheduled job.</param>
/// <param name="ownerUserId">The object representing the unique identifier of the user that owns the scheduled job.</param>
/// <param name="status">The status of the scheduled job.</param>
/// <param name="lastStartedOnUtc">The optional date and time when the task of the scheduled job last started its execution.</param>
/// <param name="lastCompletedOnUtc">The optional date and time when the task of the scheduled job last completed its execution.</param>
private ScheduledJob(ScheduledJobId id, string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId, ScheduledJobStatus status, Optional<DateTime> lastStartedOnUtc, Optional<DateTime> lastCompletedOnUtc)
: base(id)
{
Name = name;
TaskType = taskType;
Schedule = schedule;
OwnerUserId = ownerUserId;
Status = status;
LastStartedOnUtc = lastStartedOnUtc;
LastCompletedOnUtc = lastCompletedOnUtc;
_currentExecutionRunId = Optional<Guid>.None();
}
/// <summary>
/// Creates a new instance of the <see cref="ScheduledJob"/> class.
/// </summary>
/// <param name="name">The name of the scheduled job.</param>
/// <param name="taskType">The type of the task executed by the scheduled job.</param>
/// <param name="schedule">The schedule of the scheduled job.</param>
/// <param name="ownerUserId">The object representing the unique identifier of the user that owns the scheduled job.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="ScheduledJob"/>, or an error message.
/// </returns>
public static Result<ScheduledJob> Create(string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.Scheduling.ScheduledJobNameCannotBeEmpty;
return new ScheduledJob(ScheduledJobId.CreateUnique(), name, taskType, schedule, ownerUserId, ScheduledJobStatus.Added, Optional<DateTime>.None(), Optional<DateTime>.None());
}
/// <summary>
/// Creates a new instance of the <see cref="ScheduledJob"/> class, with pre-existing data.
/// </summary>
/// <param name="id">The object representing the unique identifier of the scheduled job.</param>
/// <param name="name">The name of the scheduled job.</param>
/// <param name="taskType">The type of the task executed by the scheduled job.</param>
/// <param name="schedule">The schedule of the scheduled job.</param>
/// <param name="ownerUserId">The object representing the unique identifier of the user that owns the scheduled job.</param>
/// <param name="status">The status of the scheduled job.</param>
/// <param name="lastStartedOnUtc">The optional date and time when the task of the scheduled job last started its execution.</param>
/// <param name="lastCompletedOnUtc">The optional date and time when the task of the scheduled job last completed its execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="ScheduledJob"/>, or an error message.
/// </returns>
public static Result<ScheduledJob> Create(ScheduledJobId id, string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId, ScheduledJobStatus status, Optional<DateTime> lastStartedOnUtc, Optional<DateTime> lastCompletedOnUtc)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.Scheduling.ScheduledJobNameCannotBeEmpty;
return new ScheduledJob(id, name, taskType, schedule, ownerUserId, status, lastStartedOnUtc, lastCompletedOnUtc);
}
/// <summary>
/// Marks the scheduled job as added.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> Add()
{
if (Status != ScheduledJobStatus.Added)
return Errors.Scheduling.ScheduledJobCycleAlreadyStarted;
_domainEvents.Add(new ScheduledJobAddedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Starts the execution cycle of the scheduled job.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> StartCycle()
{
if (Status == ScheduledJobStatus.Active || Status == ScheduledJobStatus.Running)
return Errors.Scheduling.ScheduledJobCycleAlreadyStarted;
Status = ScheduledJobStatus.Active;
_domainEvents.Add(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Stops the execution cycle of the scheduled job.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> StopCycle()
{
if (Status == ScheduledJobStatus.Added || Status == ScheduledJobStatus.Completed)
return Errors.Scheduling.ScheduledJobNotStarted;
ScheduledJobStatus previousStatus = Status;
Status = ScheduledJobStatus.Added;
// When the task of the scheduled job is currently executing, its execution is stopped as well, so its history row is closed.
if (previousStatus == ScheduledJobStatus.Running)
{
LastCompletedOnUtc = Optional<DateTime>.Some(DateTime.UtcNow);
_domainEvents.Add(new ScheduledJobExecutionStoppedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
}
else
_domainEvents.Add(new ScheduledJobCycleStoppedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Marks the start of a one time execution of the task of the scheduled job.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> Fire()
{
if (Status == ScheduledJobStatus.Running)
return Errors.Scheduling.ScheduledJobAlreadyRunning;
_domainEvents.Add(new ScheduledJobFiredDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Marks the scheduled job as removed.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> Remove()
{
_domainEvents.Add(new ScheduledJobRemovedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Marks the task of the scheduled job as started.
/// </summary>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> MarkExecutionStarted(bool isCycleRun)
{
if (Status == ScheduledJobStatus.Running)
return Errors.Scheduling.ScheduledJobAlreadyRunning;
Guid runId = Guid.NewGuid();
_currentExecutionRunId = Optional<Guid>.Some(runId);
Status = ScheduledJobStatus.Running;
LastStartedOnUtc = Optional<DateTime>.Some(DateTime.UtcNow);
_domainEvents.Add(new ScheduledJobExecutionStartedDomainEvent(Guid.NewGuid(), Id, runId, TaskType, isCycleRun, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Marks the task of the scheduled job as completed.
/// </summary>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> MarkExecutionCompleted(bool isCycleRun)
{
if (Status != ScheduledJobStatus.Running)
return Errors.Scheduling.CanOnlyCompleteRunningScheduledJob;
if (!_currentExecutionRunId.HasValue)
return Errors.Scheduling.CanOnlyCompleteRunningScheduledJob;
Guid runId = _currentExecutionRunId.Value;
_currentExecutionRunId = Optional<Guid>.None();
// A cycle run returns the scheduled job to its active state, where it waits for the next execution; a one time execution finishes the scheduled job.
Status = isCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed;
LastCompletedOnUtc = Optional<DateTime>.Some(DateTime.UtcNow);
_domainEvents.Add(new ScheduledJobExecutionCompletedDomainEvent(Guid.NewGuid(), Id, runId, TaskType, isCycleRun, DateTime.UtcNow));
return Result.Success;
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Represents a daily schedule for a scheduled job.
/// </summary>
public class DailySchedule : Schedule
{
/// <summary>
/// Gets the hour of the day at which the scheduled job runs.
/// </summary>
public int Hour { get; }
/// <summary>
/// Gets the minute of the hour at which the scheduled job runs.
/// </summary>
public int Minute { get; }
/// <summary>
/// Gets the type of the schedule.
/// </summary>
public override ScheduleType ScheduleType { get; } = ScheduleType.DailyAtHourAndMinute;
/// <summary>
/// Initializes a new instance of the <see cref="DailySchedule"/> class.
/// </summary>
/// <param name="hour">The hour of the day at which the scheduled job runs.</param>
/// <param name="minute">The minute of the hour at which the scheduled job runs.</param>
private DailySchedule(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
/// <summary>
/// Creates a new instance of the <see cref="DailySchedule"/> class.
/// </summary>
/// <param name="hour">The hour of the day at which the scheduled job runs.</param>
/// <param name="minute">The minute of the hour at which the scheduled job runs.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="DailySchedule"/>, or an error message.
/// </returns>
public static Result<DailySchedule> Create(int hour, int minute)
{
if (hour < 0 || hour > 23)
return Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree;
if (minute < 0 || minute > 59)
return Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine;
return new DailySchedule(hour, minute);
}
/// <summary>
/// Calculates the delay until the next execution of the scheduled job, relative to <paramref name="utcNow"/>.
/// </summary>
/// <param name="utcNow">The current UTC date and time.</param>
/// <param name="timeZone">The time zone in which the daily hour and minute of the schedule are expressed.</param>
/// <returns>The delay until the next execution of the scheduled job.</returns>
public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone)
{
DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone);
DateTime nextRunLocal = new(localNow.Year, localNow.Month, localNow.Day, Hour, Minute, 0, DateTimeKind.Unspecified);
DateTime nextRunUtc = TimeZoneInfo.ConvertTimeToUtc(nextRunLocal, timeZone);
// When the next run time already passed today, schedule the execution for the next day.
if (nextRunUtc <= utcNow)
nextRunUtc = nextRunUtc.AddDays(1);
return nextRunUtc - utcNow;
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Hour;
yield return Minute;
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Represents an interval based schedule for a scheduled job.
/// </summary>
public class IntervalSchedule : Schedule
{
/// <summary>
/// Gets the interval of the schedule, in minutes.
/// </summary>
public int IntervalMinutes { get; }
/// <summary>
/// Gets the type of the schedule.
/// </summary>
public override ScheduleType ScheduleType { get; } = ScheduleType.WithIntervalInMinutes;
/// <summary>
/// Initializes a new instance of the <see cref="IntervalSchedule"/> class.
/// </summary>
/// <param name="intervalMinutes">The interval of the schedule, in minutes.</param>
private IntervalSchedule(int intervalMinutes)
{
IntervalMinutes = intervalMinutes;
}
/// <summary>
/// Creates a new instance of the <see cref="IntervalSchedule"/> class.
/// </summary>
/// <param name="intervalMinutes">The interval of the schedule, in minutes.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="IntervalSchedule"/>, or an error message.
/// </returns>
public static Result<IntervalSchedule> Create(int intervalMinutes)
{
if (intervalMinutes <= 0)
return Errors.Scheduling.IntervalMinutesMustBePositive;
return new IntervalSchedule(intervalMinutes);
}
/// <summary>
/// Calculates the delay until the next execution of the scheduled job, relative to <paramref name="utcNow"/>.
/// </summary>
/// <param name="utcNow">The current UTC date and time.</param>
/// <param name="timeZone">The time zone in which the daily hour and minute of the schedule are expressed.</param>
/// <returns>The delay until the next execution of the scheduled job.</returns>
public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone)
{
return TimeSpan.FromMinutes(IntervalMinutes);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return IntervalMinutes;
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Represents an abstract schedule for a scheduled job.
/// </summary>
public abstract class Schedule : ValueObject
{
/// <summary>
/// Gets the type of the schedule.
/// </summary>
public abstract ScheduleType ScheduleType { get; }
/// <summary>
/// Calculates the delay until the next execution of the scheduled job, relative to <paramref name="utcNow"/>.
/// </summary>
/// <param name="utcNow">The current UTC date and time.</param>
/// <param name="timeZone">The time zone in which the daily hour and minute of the schedule are expressed.</param>
/// <returns>The delay until the next execution of the scheduled job.</returns>
public abstract TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone);
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Value object for the Id of a scheduled job.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class ScheduledJobId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private ScheduledJobId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="ScheduledJobId"/> class.
/// </summary>
/// <returns>The created <see cref="ScheduledJobId"/> instance.</returns>
public static ScheduledJobId CreateUnique()
{
return new ScheduledJobId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="ScheduledJobId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="ScheduledJobId"/> instance.</param>
/// <returns>The created <see cref="ScheduledJobId"/> instance.</returns>
public static ScheduledJobId Create(Guid value)
{
return new ScheduledJobId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}