diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs
new file mode 100644
index 00000000..5bf2c72d
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs
@@ -0,0 +1,90 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
+
+///
+/// Repository entity for a scheduled job.
+///
+[DebuggerDisplay("Id: {Id}, Status: {Status}")]
+public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets the Id of the scheduled job.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets the name of the scheduled job.
+ ///
+ public required string Name { get; init; }
+
+ ///
+ /// Gets the type of the task executed by the scheduled job.
+ ///
+ public required ScheduledTaskType TaskType { get; init; }
+
+ ///
+ /// Gets the type of the schedule of the scheduled job.
+ ///
+ public required ScheduleType ScheduleType { get; init; }
+
+ ///
+ /// Gets the interval in minutes of the schedule of the scheduled job, when its is .
+ ///
+ public int? IntervalMinutes { get; init; }
+
+ ///
+ /// Gets the hour of the schedule of the scheduled job, when its is .
+ ///
+ public int? Hour { get; init; }
+
+ ///
+ /// Gets the minute of the schedule of the scheduled job, when its is .
+ ///
+ public int? Minute { get; init; }
+
+ ///
+ /// Gets the status of the scheduled job.
+ ///
+ public required ScheduledJobStatus Status { get; init; }
+
+ ///
+ /// Gets the Id of the user that owns the scheduled job.
+ ///
+ public required Guid OwnerUserId { get; init; }
+
+ ///
+ /// Gets the optional date and time when the task of the scheduled job last started its execution.
+ ///
+ public DateTime? LastStartedOnUtc { get; init; }
+
+ ///
+ /// Gets the optional date and time when the task of the scheduled job last completed its execution.
+ ///
+ public DateTime? LastCompletedOnUtc { get; init; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs
new file mode 100644
index 00000000..e05774c9
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
+
+///
+/// Repository entity for an execution of the task of a scheduled job.
+///
+[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
+public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets the Id of the execution of the task of a scheduled job.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets the Id of the scheduled job whose task was executed.
+ ///
+ public required Guid ScheduledJobId { get; init; }
+
+ ///
+ /// Gets the type of the task that was executed.
+ ///
+ public required ScheduledTaskType TaskType { get; init; }
+
+ ///
+ /// Gets a value indicating whether the execution was triggered by the execution cycle of the scheduled job, or it was a one time execution.
+ ///
+ public required bool IsCycleRun { get; init; }
+
+ ///
+ /// Gets the date and time when the execution started.
+ ///
+ public required DateTime StartedOnUtc { get; init; }
+
+ ///
+ /// Gets the optional date and time when the execution completed.
+ ///
+ public DateTime? CompletedOnUtc { get; init; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs
new file mode 100644
index 00000000..d6817638
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs
@@ -0,0 +1,46 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
+
+///
+/// Interface for the repository for the executions of the tasks of scheduled jobs.
+///
+public interface IScheduledJobExecutionRepository : IRepository,
+ IGetByIdRepositoryAction,
+ IInsertRepositoryAction,
+ IUpdateRepositoryAction
+{
+ ///
+ /// Gets the most recent execution of the task of a scheduled job identified by that is still running, from the storage medium.
+ ///
+ /// The Id of the scheduled job whose running execution is retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the running execution of the scheduled job, or .
+ Task> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Gets the executions of the tasks of scheduled jobs that started in the interval between and , from the storage medium.
+ ///
+ /// The inclusive lower bound of the interval, in UTC.
+ /// The inclusive upper bound of the interval, in UTC.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken);
+
+ ///
+ /// Removes all the executions of the task of a scheduled job identified by , from the storage medium.
+ ///
+ /// The Id of the scheduled job whose executions are removed.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs
new file mode 100644
index 00000000..438dceb2
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
+
+///
+/// Interface for the repository for scheduled jobs.
+///
+public interface IScheduledJobRepository : IRepository,
+ IGetByIdRepositoryAction,
+ IGetAllRepositoryAction,
+ IInsertRepositoryAction,
+ IUpdateRepositoryAction,
+ IDeleteByIdRepositoryAction
+{
+ ///
+ /// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetActiveOrRunningAsync(CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
index f748d5dd..8a84bce4 100644
--- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
+++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
+using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using System.Threading;
@@ -87,6 +88,16 @@ public interface IUnitOfWork
///
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
+ ///
+ /// Gets the scheduled job repository.
+ ///
+ IScheduledJobRepository ScheduledJobRepository { get; }
+
+ ///
+ /// Gets the scheduled job execution repository.
+ ///
+ IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get; }
+
///
/// Gets the plugin repository.
///
diff --git a/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs
new file mode 100644
index 00000000..15828b20
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Scheduling;
+
+///
+/// Interface for the service that schedules and executes the tasks of scheduled jobs.
+///
+public interface IScheduledJobScheduler
+{
+ ///
+ /// Starts the execution cycle of the scheduled job identified by .
+ ///
+ /// The object representing the unique identifier of the scheduled job whose execution cycle is started.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Stops the execution cycle of the scheduled job identified by .
+ ///
+ /// The object representing the unique identifier of the scheduled job whose execution cycle is stopped.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Fires the task of the scheduled job identified by once, without affecting its execution cycle.
+ ///
+ /// The object representing the unique identifier of the scheduled job whose task is fired.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..9bba28d0
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class AddScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static AddScheduledJobCommand ToCommand(this AddScheduledJobRequest request)
+ {
+ return new AddScheduledJobCommand(
+ request.Name,
+ request.TaskType,
+ request.ScheduleType,
+ request.IntervalMinutes,
+ request.Hour,
+ request.Minute
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..d00d8df1
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class FireScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static FireScheduledJobCommand ToCommand(this FireScheduledJobRequest request)
+ {
+ return new FireScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs
new file mode 100644
index 00000000..0a3ae563
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class GetScheduledJobHistoryRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetScheduledJobHistoryQuery ToQuery(this GetScheduledJobHistoryRequest request)
+ {
+ return new GetScheduledJobHistoryQuery(
+ request.From,
+ request.To
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..ea6432a9
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class RemoveScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static RemoveScheduledJobCommand ToCommand(this RemoveScheduledJobRequest request)
+ {
+ return new RemoveScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
new file mode 100644
index 00000000..78be15a5
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobEntityMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ ///
+ /// An containing either a converted , or an error message.
+ ///
+ public static Result ToDomainEntity(this ScheduledJobEntity repositoryEntity)
+ {
+ Result scheduleResult = CreateSchedule(repositoryEntity);
+ if (scheduleResult.IsFailure)
+ return scheduleResult.Errors;
+
+ return ScheduledJob.Create(
+ ScheduledJobId.Create(repositoryEntity.Id),
+ repositoryEntity.Name,
+ repositoryEntity.TaskType,
+ scheduleResult.Value,
+ UserId.Create(repositoryEntity.OwnerUserId),
+ repositoryEntity.Status,
+ Optional.FromNullable(repositoryEntity.LastStartedOnUtc),
+ Optional.FromNullable(repositoryEntity.LastCompletedOnUtc)
+ );
+ }
+
+ ///
+ /// Converts to a collection of .
+ ///
+ /// The repository entities to be converted.
+ ///
+ /// An containing either a collection of converted , or an error message.
+ ///
+ public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities)
+ {
+ return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity());
+ }
+
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The converted scheduled job response.
+ public static ScheduledJobResponse ToResponse(this ScheduledJobEntity repositoryEntity)
+ {
+ return new ScheduledJobResponse(
+ repositoryEntity.Id,
+ repositoryEntity.Name,
+ repositoryEntity.TaskType,
+ repositoryEntity.ScheduleType,
+ repositoryEntity.IntervalMinutes,
+ repositoryEntity.Hour,
+ repositoryEntity.Minute,
+ repositoryEntity.Status,
+ repositoryEntity.LastStartedOnUtc,
+ repositoryEntity.LastCompletedOnUtc
+ );
+ }
+
+ ///
+ /// Creates the schedule of from its flattened schedule properties.
+ ///
+ /// The repository entity whose schedule is created.
+ ///
+ /// An containing either a created , or an error message.
+ ///
+ private static Result CreateSchedule(ScheduledJobEntity repositoryEntity)
+ {
+ if (repositoryEntity.ScheduleType == ScheduleType.WithIntervalInMinutes)
+ {
+ Result intervalScheduleResult = IntervalSchedule.Create(repositoryEntity.IntervalMinutes ?? 0);
+ if (intervalScheduleResult.IsFailure)
+ return intervalScheduleResult.Errors;
+ return Result.From(intervalScheduleResult.Value);
+ }
+
+ Result dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0);
+ if (dailyScheduleResult.IsFailure)
+ return dailyScheduleResult.Errors;
+ return Result.From(dailyScheduleResult.Value);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
new file mode 100644
index 00000000..2ac77c66
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobExecutionEntityMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The converted execution response.
+ public static ScheduledJobExecutionResponse ToResponse(this ScheduledJobExecutionEntity repositoryEntity)
+ {
+ return new ScheduledJobExecutionResponse(
+ repositoryEntity.Id,
+ repositoryEntity.ScheduledJobId,
+ repositoryEntity.TaskType,
+ repositoryEntity.IsCycleRun,
+ repositoryEntity.StartedOnUtc,
+ repositoryEntity.CompletedOnUtc
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs
new file mode 100644
index 00000000..3099ea14
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs
@@ -0,0 +1,93 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The domain entity to be converted.
+ /// The converted repository entity.
+ public static ScheduledJobEntity ToRepositoryEntity(this ScheduledJob domainEntity)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = domainEntity.Id.Value,
+ Name = domainEntity.Name,
+ TaskType = domainEntity.TaskType,
+ ScheduleType = domainEntity.Schedule.ScheduleType,
+ IntervalMinutes = GetIntervalMinutes(domainEntity),
+ Hour = GetHour(domainEntity),
+ Minute = GetMinute(domainEntity),
+ Status = domainEntity.Status,
+ OwnerUserId = domainEntity.OwnerUserId.Value,
+ LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
+ LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null,
+ CreatedOnUtc = domainEntity.CreatedOnUtc,
+ CreatedBy = Guid.Empty,
+ UpdatedOnUtc = domainEntity.UpdatedOnUtc,
+ UpdatedBy = Guid.Empty
+ };
+ }
+
+ ///
+ /// Converts to .
+ ///
+ /// The domain entity to be converted.
+ /// The converted scheduled job response.
+ public static ScheduledJobResponse ToResponse(this ScheduledJob domainEntity)
+ {
+ return new ScheduledJobResponse(
+ domainEntity.Id.Value,
+ domainEntity.Name,
+ domainEntity.TaskType,
+ domainEntity.Schedule.ScheduleType,
+ GetIntervalMinutes(domainEntity),
+ GetHour(domainEntity),
+ GetMinute(domainEntity),
+ domainEntity.Status,
+ domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
+ domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null
+ );
+ }
+
+ ///
+ /// Gets the interval in minutes of the schedule of , when it is an interval schedule.
+ ///
+ /// The scheduled job whose schedule interval is retrieved.
+ /// The interval in minutes of the schedule, or when the schedule is not an interval schedule.
+ private static int? GetIntervalMinutes(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is IntervalSchedule intervalSchedule ? intervalSchedule.IntervalMinutes : null;
+ }
+
+ ///
+ /// Gets the hour of the schedule of , when it is a daily schedule.
+ ///
+ /// The scheduled job whose schedule hour is retrieved.
+ /// The hour of the schedule, or when the schedule is not a daily schedule.
+ private static int? GetHour(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Hour : null;
+ }
+
+ ///
+ /// Gets the minute of the schedule of , when it is a daily schedule.
+ ///
+ /// The scheduled job whose schedule minute is retrieved.
+ /// The minute of the schedule, or when the schedule is not a daily schedule.
+ private static int? GetMinute(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Minute : null;
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..067665ec
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class StartScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static StartScheduledJobCommand ToCommand(this StartScheduledJobRequest request)
+ {
+ return new StartScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..488a699a
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class StopScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static StopScheduledJobCommand ToCommand(this StopScheduledJobRequest request)
+ {
+ return new StopScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs
new file mode 100644
index 00000000..becfb43d
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Command for adding a scheduled job.
+///
+/// The name of the scheduled job.
+/// The type of the task executed by the scheduled job.
+/// The type of the schedule of the scheduled job.
+/// The interval in minutes of the schedule, when the schedule type is .
+/// The hour of the schedule, when the schedule type is .
+/// The minute of the schedule, when the schedule type is .
+[DebuggerDisplay("Name: {Name}")]
+public record AddScheduledJobCommand(
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..aa5167b7
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs
@@ -0,0 +1,122 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Handler for the command to add a scheduled job.
+///
+public class AddScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public AddScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to add a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a successfully created , or an error message.
+ ///
+ public async Task> HandleAsync(AddScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can schedule jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Create the schedule of the scheduled job, based on its type.
+ Result scheduleResult;
+ if (command.ScheduleType == ScheduleType.WithIntervalInMinutes)
+ {
+ Result intervalScheduleResult = IntervalSchedule.Create(command.IntervalMinutes ?? 0);
+ if (intervalScheduleResult.IsFailure)
+ return intervalScheduleResult.Errors;
+ scheduleResult = Result.From(intervalScheduleResult.Value);
+ }
+ else if (command.ScheduleType == ScheduleType.DailyAtHourAndMinute)
+ {
+ Result dailyScheduleResult = DailySchedule.Create(command.Hour ?? 0, command.Minute ?? 0);
+ if (dailyScheduleResult.IsFailure)
+ return dailyScheduleResult.Errors;
+ scheduleResult = Result.From(dailyScheduleResult.Value);
+ }
+ else
+ return DomainErrors.Scheduling.InvalidScheduleType;
+
+ // Create a domain scheduled job object.
+ Result createScheduledJobResult = ScheduledJob.Create(command.Name, command.TaskType, scheduleResult.Value, UserId.Create(userId));
+ if (createScheduledJobResult.IsFailure)
+ return createScheduledJobResult.Errors;
+ createScheduledJobResult.Value.Add();
+
+ // Convert the domain scheduled job to a repository entity, insert it, and save the changes.
+ ScheduledJobEntity persistenceScheduledJob = createScheduledJobResult.Value.ToRepositoryEntity();
+ Result insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (insertScheduledJobResult.IsFailure)
+ return insertScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return createScheduledJobResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..04a30b31
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs
@@ -0,0 +1,64 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class AddScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public AddScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.Name)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty)
+ .MaximumLength(80)
+ .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
+
+ RuleFor(command => command.TaskType)
+ .IsInEnum()
+ .WithError(Errors.Scheduling.InvalidScheduleType);
+
+ RuleFor(command => command.ScheduleType)
+ .IsInEnum()
+ .WithError(Errors.Scheduling.InvalidScheduleType);
+
+ RuleFor(command => command.IntervalMinutes)
+ .Must(intervalMinutes => intervalMinutes is null || intervalMinutes > 0)
+ .WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
+ .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
+
+ RuleFor(command => command.IntervalMinutes)
+ .Must(intervalMinutes => intervalMinutes is not null)
+ .WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
+ .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
+
+ RuleFor(command => command.Hour)
+ .Must(hour => hour is not null)
+ .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Minute)
+ .Must(minute => minute is not null)
+ .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Hour)
+ .InclusiveBetween(0, 23)
+ .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Minute)
+ .InclusiveBetween(0, 59)
+ .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs
new file mode 100644
index 00000000..f10430d1
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Command for firing the task of a scheduled job once, without affecting its execution cycle.
+///
+/// The unique identifier of the scheduled job whose task is fired.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record FireScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..86585082
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Handler for the command to fire the task of a scheduled job once.
+///
+public class FireScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public FireScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to fire the task of a scheduled job once.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(FireScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can fire scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and guard the fire against a currently running task.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result fireResult = scheduledJobDomainResult.Value.Fire();
+ if (fireResult.IsFailure)
+ return fireResult.Errors;
+
+ // Queue the domain event that requests a one time execution of the task of the scheduled job.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..425b31ee
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class FireScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public FireScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs
new file mode 100644
index 00000000..ff0e74c8
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Command for removing a scheduled job.
+///
+/// The unique identifier of the scheduled job to remove.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record RemoveScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..ba19721c
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Handler for the command to remove a scheduled job.
+///
+public class RemoveScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public RemoveScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IScheduledJobScheduler scheduledJobScheduler,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to remove a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An representing either a successful operation, or an error.
+ ///
+ public async Task> HandleAsync(RemoveScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can remove scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Stop the execution cycle of the scheduled job, if it has one.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
+
+ // Remove the executions and the scheduled job itself from the storage medium.
+ Result deleteExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (deleteExecutionsResult.IsFailure)
+ return deleteExecutionsResult.Errors;
+ Result deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (deleteScheduledJobResult.IsFailure)
+ return deleteScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ scheduledJobDomainResult.Value.Remove();
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..8980ee94
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class RemoveScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public RemoveScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs
new file mode 100644
index 00000000..14b8203b
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Command for starting the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is started.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StartScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..f5c0be2f
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs
@@ -0,0 +1,109 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Handler for the command to start the execution cycle of a scheduled job.
+///
+public class StartScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public StartScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to start the execution cycle of a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(StartScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can start scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and start its execution cycle.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result startCycleResult = scheduledJobDomainResult.Value.StartCycle();
+ if (startCycleResult.IsFailure)
+ return startCycleResult.Errors;
+
+ // Persist the new status of the scheduled job.
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ return updateScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..2b09e00b
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StartScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StartScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs
new file mode 100644
index 00000000..2ee36eed
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Command for stopping the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is stopped.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StopScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..177e0865
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs
@@ -0,0 +1,116 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Handler for the command to stop the execution cycle of a scheduled job.
+///
+public class StopScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public StopScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IScheduledJobScheduler scheduledJobScheduler,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to stop the execution cycle of a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(StopScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can stop scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and stop its execution cycle.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result stopCycleResult = scheduledJobDomainResult.Value.StopCycle();
+ if (stopCycleResult.IsFailure)
+ return stopCycleResult.Errors;
+
+ // Persist the new status of the scheduled job.
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ return updateScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Stop the execution cycle in the scheduler service.
+ await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..03681f46
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StopScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StopScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs
new file mode 100644
index 00000000..4a523bd2
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when a scheduled job is added.
+///
+public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when a scheduled job is added.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs
new file mode 100644
index 00000000..974f02ed
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution cycle of a scheduled job is started.
+///
+public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobCycleStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IScheduledJobScheduler scheduledJobScheduler, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ }
+
+ ///
+ /// Handles the event raised when the execution cycle of a scheduled job is started.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobCycleStartedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Start the execution cycle in the scheduler service, which runs the task of the scheduled job once immediately and then on its schedule.
+ await _scheduledJobScheduler.StartCycleAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs
new file mode 100644
index 00000000..a04da146
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution cycle of a scheduled job is stopped.
+///
+public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobCycleStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the execution cycle of a scheduled job is stopped.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs
new file mode 100644
index 00000000..ebfaa878
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs
@@ -0,0 +1,147 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job completes its execution.
+///
+public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionCompletedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job completes its execution.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Get the scheduled job from the repository.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
+ if (getScheduledJobResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
+ ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
+
+ // A cycle run returns the scheduled job to its active status, a one time execution completes it.
+ ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed;
+ ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc);
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
+
+ // Mark the execution of the task of the scheduled job as completed.
+ Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false);
+ if (getExecutionResult.IsFailure)
+ throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors);
+ if (getExecutionResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound);
+ ScheduledJobExecutionEntity execution = getExecutionResult.Value;
+ ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc);
+ Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
+ if (updateExecutionResult.IsFailure)
+ throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Notify the SignalR clients about the current scheduled jobs and the completed execution.
+ await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
+ await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Creates a copy of with the provided status and timestamps.
+ ///
+ /// The scheduled job to copy.
+ /// The status of the copy.
+ /// The last start time of the copy.
+ /// The last completion time of the copy.
+ /// The copy of the scheduled job.
+ private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = scheduledJob.Id,
+ Name = scheduledJob.Name,
+ TaskType = scheduledJob.TaskType,
+ ScheduleType = scheduledJob.ScheduleType,
+ IntervalMinutes = scheduledJob.IntervalMinutes,
+ Hour = scheduledJob.Hour,
+ Minute = scheduledJob.Minute,
+ Status = status,
+ OwnerUserId = scheduledJob.OwnerUserId,
+ LastStartedOnUtc = lastStartedOnUtc,
+ LastCompletedOnUtc = lastCompletedOnUtc,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
+ UpdatedBy = scheduledJob.UpdatedBy
+ };
+ }
+
+ ///
+ /// Creates a copy of with the provided completion time.
+ ///
+ /// The execution to copy.
+ /// The completion time of the copy.
+ /// The copy of the execution.
+ private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
+ {
+ return new ScheduledJobExecutionEntity
+ {
+ Id = execution.Id,
+ ScheduledJobId = execution.ScheduledJobId,
+ TaskType = execution.TaskType,
+ IsCycleRun = execution.IsCycleRun,
+ StartedOnUtc = execution.StartedOnUtc,
+ CompletedOnUtc = completedOnUtc,
+ CreatedOnUtc = execution.CreatedOnUtc,
+ CreatedBy = execution.CreatedBy,
+ UpdatedOnUtc = execution.UpdatedOnUtc,
+ UpdatedBy = execution.UpdatedBy
+ };
+ }
+
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs
new file mode 100644
index 00000000..525bfdcf
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs
@@ -0,0 +1,129 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job starts its execution.
+///
+public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job starts its execution.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Get the scheduled job from the repository.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
+ if (getScheduledJobResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
+ ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
+
+ // Update the scheduled job with its running status and the start time of the execution.
+ ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc);
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
+
+ // Insert the execution of the task of the scheduled job into the repository.
+ ScheduledJobExecutionEntity execution = new()
+ {
+ Id = domainEvent.RunId,
+ ScheduledJobId = scheduledJob.Id,
+ TaskType = scheduledJob.TaskType,
+ IsCycleRun = domainEvent.IsCycleRun,
+ StartedOnUtc = domainEvent.StartedOnUtc,
+ CompletedOnUtc = null,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = null,
+ UpdatedBy = null
+ };
+ Result insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false);
+ if (insertExecutionResult.IsFailure)
+ throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors);
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Notify the SignalR clients about the current scheduled jobs and the started execution.
+ await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
+ await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Creates a copy of with the provided status and timestamps.
+ ///
+ /// The scheduled job to copy.
+ /// The status of the copy.
+ /// The last start time of the copy.
+ /// The last completion time of the copy.
+ /// The copy of the scheduled job.
+ private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = scheduledJob.Id,
+ Name = scheduledJob.Name,
+ TaskType = scheduledJob.TaskType,
+ ScheduleType = scheduledJob.ScheduleType,
+ IntervalMinutes = scheduledJob.IntervalMinutes,
+ Hour = scheduledJob.Hour,
+ Minute = scheduledJob.Minute,
+ Status = status,
+ OwnerUserId = scheduledJob.OwnerUserId,
+ LastStartedOnUtc = lastStartedOnUtc,
+ LastCompletedOnUtc = lastCompletedOnUtc,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
+ UpdatedBy = scheduledJob.UpdatedBy
+ };
+ }
+
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs
new file mode 100644
index 00000000..7da598e4
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs
@@ -0,0 +1,79 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution of the task of a scheduled job is stopped while it is running.
+///
+public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the execution of the task of a scheduled job is stopped while it is running.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Close the execution history row of the stopped execution, if it exists.
+ Result getOpenExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository
+ .GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getOpenExecutionResult.IsFailure)
+ throw new EventualConsistencyException(getOpenExecutionResult.FirstError, getOpenExecutionResult.Errors);
+ if (getOpenExecutionResult.Value is not null)
+ {
+ ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value;
+ ScheduledJobExecutionEntity updatedExecution = new()
+ {
+ Id = execution.Id,
+ ScheduledJobId = execution.ScheduledJobId,
+ TaskType = execution.TaskType,
+ IsCycleRun = execution.IsCycleRun,
+ StartedOnUtc = execution.StartedOnUtc,
+ CompletedOnUtc = domainEvent.OccurredOnUtc,
+ CreatedOnUtc = execution.CreatedOnUtc,
+ CreatedBy = execution.CreatedBy,
+ UpdatedOnUtc = execution.UpdatedOnUtc,
+ UpdatedBy = execution.UpdatedBy
+ };
+ Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
+ if (updateExecutionResult.IsFailure)
+ throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ // Notify the SignalR clients about the current list of scheduled jobs.
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs
new file mode 100644
index 00000000..aa29481e
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job is fired once.
+///
+public class ScheduledJobFiredDomainEventHandler : IDomainEventHandler
+{
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ public ScheduledJobFiredDomainEventHandler(IScheduledJobScheduler scheduledJobScheduler)
+ {
+ _scheduledJobScheduler = scheduledJobScheduler;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job is fired once.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobFiredDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Start a one time execution of the task of the scheduled job in the scheduler service.
+ await _scheduledJobScheduler.RunOnceAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs
new file mode 100644
index 00000000..892a64f4
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when a scheduled job is removed.
+///
+public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobRemovedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when a scheduled job is removed.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs
new file mode 100644
index 00000000..4251a142
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.Scheduling;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Notifications;
+
+///
+/// Interface for the class used to notify SignalR clients about the scheduled jobs and their executions.
+///
+public interface IScheduledJobNotifier
+{
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// The current list of scheduled jobs.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken);
+
+ ///
+ /// Notifies the SignalR clients about an execution of the task of a scheduled job that started.
+ ///
+ /// The execution of the task of the scheduled job that started.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
+
+ ///
+ /// Notifies the SignalR clients about an execution of the task of a scheduled job that completed.
+ ///
+ /// The execution of the task of the scheduled job that completed.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs
new file mode 100644
index 00000000..edac9854
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+
+///
+/// Query for getting the history of the executions of the tasks of scheduled jobs.
+///
+/// The optional inclusive lower bound of the interval for which the history is requested.
+/// The optional inclusive upper bound of the interval for which the history is requested.
+[DebuggerDisplay("From: {From}, To: {To}")]
+public record GetScheduledJobHistoryQuery(
+ DateTime? From,
+ DateTime? To
+) : IQuery;
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs
new file mode 100644
index 00000000..bb9378e9
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs
@@ -0,0 +1,76 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+
+///
+/// Handler for the query to get the history of the executions of the tasks of scheduled jobs.
+///
+public class GetScheduledJobHistoryQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public GetScheduledJobHistoryQueryHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the history of the executions of the tasks of scheduled jobs.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the execution history, or an error.
+ ///
+ public async Task>> HandleAsync(GetScheduledJobHistoryQuery query, CancellationToken cancellationToken)
+ {
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can get the history of scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // The lower bound defaults to one day before the upper bound, which defaults to now.
+ DateTime toUtc = query.To ?? DateTime.UtcNow;
+ DateTime fromUtc = query.From ?? toUtc.AddDays(-1);
+
+ // Get the executions from the storage medium.
+ Result> getExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByTimeRangeAsync(fromUtc, toUtc, cancellationToken).ConfigureAwait(false);
+ if (getExecutionsResult.IsFailure)
+ return getExecutionsResult.Errors;
+
+ return Result.From(getExecutionsResult.Value.Select(execution => execution.ToResponse()));
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs
new file mode 100644
index 00000000..99ca2129
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs
@@ -0,0 +1,12 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
+
+///
+/// Query for getting the list of scheduled jobs.
+///
+[DebuggerDisplay("GetScheduledJobsQuery")]
+public record GetScheduledJobsQuery : IQuery;
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs
new file mode 100644
index 00000000..9991ac07
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
+
+///
+/// Handler for the query to get the list of scheduled jobs.
+///
+public class GetScheduledJobsQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public GetScheduledJobsQueryHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the list of scheduled jobs.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the list of scheduled jobs, or an error.
+ ///
+ public async Task>> HandleAsync(GetScheduledJobsQuery query, CancellationToken cancellationToken)
+ {
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can get the list of scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled jobs from the storage medium.
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ return getScheduledJobsResult.Errors;
+
+ return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse()));
+ }
+}
diff --git a/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs
new file mode 100644
index 00000000..e80fafb5
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to add a scheduled job.
+///
+/// The name of the scheduled job. Required.
+/// The type of the task executed by the scheduled job. Required.
+/// The type of the schedule of the scheduled job. Required.
+/// The interval in minutes of the schedule, required when is .
+/// The hour of the schedule, required when is .
+/// The minute of the schedule, required when is .
+[DebuggerDisplay("Name: {Name}")]
+public record AddScheduledJobRequest(
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs
new file mode 100644
index 00000000..53187070
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to fire the task of a scheduled job once, without affecting its execution cycle.
+///
+/// The unique identifier of the scheduled job whose task is fired. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record FireScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs
new file mode 100644
index 00000000..e95b9f94
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to get the history of the executions of the tasks of scheduled jobs.
+///
+/// The inclusive lower bound of the interval for which the history is requested. Optional.
+/// The inclusive upper bound of the interval for which the history is requested. Optional.
+[DebuggerDisplay("From: {From}, To: {To}")]
+public record GetScheduledJobHistoryRequest(
+ DateTime? From,
+ DateTime? To
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs
new file mode 100644
index 00000000..5b3dd987
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to remove a scheduled job.
+///
+/// The unique identifier of the scheduled job to remove. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record RemoveScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs
new file mode 100644
index 00000000..63448b47
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to start the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is started. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StartScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs
new file mode 100644
index 00000000..36c3f0af
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to stop the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is stopped. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StopScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs
new file mode 100644
index 00000000..4f33a189
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.Scheduling;
+
+///
+/// Represents an execution of the task of a scheduled job.
+///
+/// The unique identifier of the execution.
+/// The unique identifier of the scheduled job whose task was executed.
+/// The type of the task that was executed.
+/// when the execution was triggered by the execution cycle of the scheduled job, when it was a one time execution.
+/// The date and time when the execution started.
+/// The optional date and time when the execution completed.
+[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
+public record ScheduledJobExecutionResponse(
+ Guid Id,
+ Guid ScheduledJobId,
+ ScheduledTaskType TaskType,
+ bool IsCycleRun,
+ DateTime StartedOnUtc,
+ DateTime? CompletedOnUtc
+);
diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs
new file mode 100644
index 00000000..c1c53a2b
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs
@@ -0,0 +1,34 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.Scheduling;
+
+///
+/// Represents a scheduled job response.
+///
+/// The unique identifier of the scheduled job.
+/// The name of the scheduled job.
+/// The type of the task executed by the scheduled job.
+/// The type of the schedule of the scheduled job.
+/// The interval in minutes of the schedule of the scheduled job, when its is .
+/// The hour of the schedule of the scheduled job, when its is .
+/// The minute of the schedule of the scheduled job, when its is .
+/// The status of the scheduled job.
+/// The optional date and time when the task of the scheduled job last started its execution.
+/// The optional date and time when the task of the scheduled job last completed its execution.
+[DebuggerDisplay("Id: {Id}, Name: {Name}, Status: {Status}")]
+public record ScheduledJobResponse(
+ Guid Id,
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute,
+ ScheduledJobStatus Status,
+ DateTime? LastStartedOnUtc,
+ DateTime? LastCompletedOnUtc
+);