diff --git a/CLAUDE.md b/CLAUDE.md
index f3aa56a..23a7d9c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -11,6 +11,7 @@ conventions: docs/MIGRATION.md. Table definitions: docs/schema/NTP.md and NAFITH
- `src/NTP.Infrastructure` Oracle + Dapper repositories (raw SQL), gateways (TCS, IVR, notifications), file store
- `src/NTP.Domain` entities and rules; `tests/NTP.Tests` xUnit (283 tests at hand-over)
- `web/src/features/grains-{orders,permits,registry,reports}` screens (metadata-driven DataGrid / MetaForm in `web/src/components`), `web/src/shell` menu, header, home
+- `src/NTP.*/Jobs` + `web/src/features/jobs` scheduled jobs (SU screen `/jobs`; catalog in `JobCatalog`; tables from `db/grains-jobs.sql`)
- `db/*.sql` one-off permission / role scripts (run by hand per environment, not by the app); `deploy/` Docker + Jenkins (see `Jenkinsfile`)
## Commands (Windows; Git Bash or PowerShell)
diff --git a/db/grains-jobs.sql b/db/grains-jobs.sql
new file mode 100644
index 0000000..4af3bd3
--- /dev/null
+++ b/db/grains-jobs.sql
@@ -0,0 +1,53 @@
+-- Scheduled jobs (screen "المهام المجدولة", SU only). Run once per database in the PRIMARY schema (NAFITHTCS). Safe to re-run; not run by the app.
+-- Until this script has run the scheduler stays idle (one warning in the API log) and the screen shows a message.
+--
+-- GRAINS_JOBS one row per job: stopped / started, schedule, last run. Rows are created by the screen, nothing to seed.
+-- GRAINS_JOB_RUNS history of every run (kept 90 days by the application).
+--
+-- Jobs (ports of the legacy jobs\*.cfm files): activate-company-destinations, close-old-permits, fill-company-shares.
+-- Schedule: SCHEDULETYPE = 'INTERVAL' (INTERVALMINUTES) or 'DAILY' (DAILYTIMES = 'HH:mm,HH:mm', database server time).
+
+DECLARE
+ PROCEDURE ddl(p_sql VARCHAR2) IS
+ BEGIN
+ EXECUTE IMMEDIATE p_sql;
+ EXCEPTION
+ WHEN OTHERS THEN
+ -- already there: name in use (955), column list already indexed (1408)
+ IF SQLCODE NOT IN (-955, -1408) THEN RAISE; END IF;
+ END;
+BEGIN
+ ddl('CREATE TABLE GRAINS_JOBS (
+ JOBKEY VARCHAR2(50) NOT NULL,
+ ENABLED NUMBER(1) DEFAULT 0 NOT NULL,
+ SCHEDULETYPE VARCHAR2(10),
+ INTERVALMINUTES NUMBER(8),
+ DAILYTIMES VARCHAR2(200),
+ LASTSTARTDATE DATE,
+ LASTENDDATE DATE,
+ LASTSTATUS VARCHAR2(20),
+ LASTMESSAGE VARCHAR2(500),
+ LASTCOUNT NUMBER(10),
+ UPDATEDATE DATE,
+ UPDATEDBY VARCHAR2(50),
+ CONSTRAINT PK_GRAINS_JOBS PRIMARY KEY (JOBKEY)
+ )');
+
+ ddl('CREATE TABLE GRAINS_JOB_RUNS (
+ ID NUMBER(12) NOT NULL,
+ JOBKEY VARCHAR2(50) NOT NULL,
+ STARTDATE DATE NOT NULL,
+ ENDDATE DATE,
+ STATUS VARCHAR2(20),
+ ROWSAFFECTED NUMBER(10),
+ MESSAGE VARCHAR2(500),
+ TRIGGEREDBY VARCHAR2(50),
+ CONSTRAINT PK_GRAINS_JOB_RUNS PRIMARY KEY (ID)
+ )');
+
+ ddl('CREATE SEQUENCE SEQ_GRAINS_JOB_RUNS START WITH 1 INCREMENT BY 1 NOCACHE');
+ ddl('CREATE INDEX IX_GRAINS_JOB_RUNS_KEY ON GRAINS_JOB_RUNS (JOBKEY, ID)');
+END;
+/
+
+-- Stop a job from SQL if the screen is not reachable: UPDATE GRAINS_JOBS SET ENABLED = 0 WHERE JOBKEY = 'close-old-permits'; COMMIT;
diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md
index bcc5536..dc9a771 100644
--- a/docs/ENVIRONMENTS.md
+++ b/docs/ENVIRONMENTS.md
@@ -54,6 +54,7 @@ Apply these scripts once per database (not run by the application), in this orde
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)
5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run)
5c. `db/role-co.sql` - new role CO with the same rights as GTO: role row (NTP schema) + copy of every GTO row in GRAINS_SCREEN_PERMISSIONS (safe to re-run)
+7. `db/grains-jobs.sql` - tables of the scheduled jobs (`GRAINS_JOBS`, `GRAINS_JOB_RUNS`), primary schema. Without it the scheduler stays idle. Jobs are then started, stopped and timed on the SU screen "المهام المجدولة" (`/jobs`); nothing runs until a job is started there. `Jobs:SchedulerEnabled=false` (set in appsettings.Development.json) switches the scheduler loop off for a process
6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run)
**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU
diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md
index fc7d146..817379a 100644
--- a/docs/HANDOVER.md
+++ b/docs/HANDOVER.md
@@ -11,6 +11,7 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
- **Reports:** the two GTO reports (ارسالية عطاء التموين, ملخص التوزيع) and turn reports (translated values, centred counters).
- **Permits / distribution:** distribution reviewed twice against legacy and fixed (BlCategory bind, General Cargo exclusion, OPEN guards, queue cursor reset at sign-in, per-category confirmation, process-with-destination dropdowns + server check); voice call (الاتصال الصوتي) uses the legacy SOAP call; dialer callback hardened.
- **Security pass:** accept / reject / cancel-confirmation staff-only, submit needs REQST, company-access null check, seed / check-trucks SU-only, attachment download scoped to the company.
+- **Scheduled jobs:** SU screen `/jobs` ("المهام المجدولة") starts / stops the three legacy jobs (`activateGrainsDestination`, `GRAINS_Close_Old_Permits` - ported new, `parseGrainsPermits`) and sets their running time: every N minutes / hours, or at fixed times of the day (database server time). Code: `src/NTP.Application/Jobs` (catalog, schedule rules, service), `src/NTP.Infrastructure/Jobs` (20-second scheduler loop, runner), `JobsController`, `web/src/features/jobs`. Needs `db/grains-jobs.sql` first. The lock is a database row, so two API instances never run one job twice. Add a job = one entry in `JobCatalog`. The old config-driven `GrainsPermitJobsWorker` is not registered and superseded by this.
- **Operations:** unexpected 5xx errors go to `SYSTEM_ERRORS`; containers run with `TZ=Asia/Amman`.
- **Roles:** `CO` was given the same code-level rights as `GTO` (see 3.1).
- Last local commit at hand-over: `bf1c04b`. **It may not be pushed** (Claude sessions cannot authenticate to Gitea): run `git log origin/main..HEAD` and push it.
@@ -28,6 +29,8 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run).
## 3. Open decisions and known gaps
+### 3.0 Scheduled jobs: untested parts
+The schedule rules are unit-tested and the close-old-permits SQL was run read-only on QA, but the job tables did not exist when this was written: run `db/grains-jobs.sql`, then try the screen (save a time, start, run now, history) on QA. Close-old-permits differs from legacy in two safe ways: a permit found by two of its four groups is closed once, and it is closed only while it still has the status it was found with.
### 3.1 Role CO
`CO` already existed in the database ("مدير العمليات وخدمة الجمهور", own group id 149, stakeholder 61, 29 mostly oil-related actions, 1 user) and the legacy menu uses it in many places. The code now treats CO like GTO, and `GRAINS_SCREEN_PERMISSIONS` already has the same 27 rows for both. **Decide** whether that user should really get GTO's grains authority or whether a new role code is wanted. Also unresolved: CO's legacy group has none of the registry actions 66-71 / 107, so accept / revoke of trucks, trailers, drivers and destinations are off for CO; `db/role-co.sql` does not create `GROUPS` / `GROUP_ACTIONS` rows.
diff --git a/src/NTP.Api/Controllers/V1/Grains/JobsController.cs b/src/NTP.Api/Controllers/V1/Grains/JobsController.cs
new file mode 100644
index 0000000..d644382
--- /dev/null
+++ b/src/NTP.Api/Controllers/V1/Grains/JobsController.cs
@@ -0,0 +1,38 @@
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using NTP.Application.Jobs;
+
+namespace NTP.Api.Controllers.V1.Grains;
+
+///
+/// Scheduled jobs (ports of the legacy jobs\*.cfm files): list, set the running time, start / stop, run now, run history.
+/// Super users only. Nothing runs until a job is started here.
+///
+[ApiController]
+[ApiVersion(1.0)]
+[Route("api/v{version:apiVersion}/grains/jobs")]
+[Produces("application/json")]
+[Authorize(Roles = "SU")]
+public sealed class JobsController(IJobService jobs) : ControllerBase
+{
+ [HttpGet]
+ public Task> List(CancellationToken ct) => jobs.ListAsync(ct);
+
+ /// Running time: every N minutes (INTERVAL) or at fixed times of the day (DAILY, HH:mm).
+ [HttpPut("{key}")]
+ public Task SaveSchedule(string key, SaveJobScheduleRequest request, CancellationToken ct) => jobs.SaveScheduleAsync(key, request, ct);
+
+ [HttpPost("{key}/start")]
+ public Task Start(string key, CancellationToken ct) => jobs.StartAsync(key, ct);
+
+ [HttpPost("{key}/stop")]
+ public Task Stop(string key, CancellationToken ct) => jobs.StopAsync(key, ct);
+
+ /// Starts the job now in the background, whether it is started or stopped; refuses when it is already running.
+ [HttpPost("{key}/run")]
+ public Task Run(string key, CancellationToken ct) => jobs.RunNowAsync(key, ct);
+
+ [HttpGet("{key}/runs")]
+ public Task> Runs(string key, CancellationToken ct) => jobs.RunsAsync(key, ct);
+}
diff --git a/src/NTP.Api/appsettings.Development.json b/src/NTP.Api/appsettings.Development.json
index 545ff69..b092037 100644
--- a/src/NTP.Api/appsettings.Development.json
+++ b/src/NTP.Api/appsettings.Development.json
@@ -2,6 +2,8 @@
"Auth": {
"SuperUsers": [ "samer", "QA", "MATHHER" ]
},
+ // the job scheduler never runs on a developer machine (a shared database would run its jobs twice); "run now" still works
+ "Jobs": { "SchedulerEnabled": false },
"Logging": {
"LogLevel": {
"Default": "Information",
diff --git a/src/NTP.Application/Grains/Permits/PermitJobsService.cs b/src/NTP.Application/Grains/Permits/PermitJobsService.cs
new file mode 100644
index 0000000..a7baa22
--- /dev/null
+++ b/src/NTP.Application/Grains/Permits/PermitJobsService.cs
@@ -0,0 +1,50 @@
+using NTP.Application.Abstractions;
+using NTP.Domain.Grains.Permits;
+
+namespace NTP.Application.Grains.Permits;
+
+/// A permit that jobs/GRAINS_Close_Old_Permits.cfm closes.
+public sealed class OldPermitRow
+{
+ public long Id { get; set; }
+ public string? Status { get; set; }
+}
+
+public interface IPermitJobsRepository
+{
+ /// The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules).
+ Task> GetOldPermitsToCloseAsync(CancellationToken ct = default);
+
+ /// Sets CLOSE only while the permit still has the status it was found with; returns the rows changed.
+ Task CloseAsync(long permitId, string previousStatus, CancellationToken ct = default);
+}
+
+public interface IPermitJobsService
+{
+ /// jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed.
+ Task CloseOldPermitsAsync(CancellationToken ct = default);
+}
+
+public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService
+{
+ public async Task CloseOldPermitsAsync(CancellationToken ct = default)
+ {
+ var rows = await repo.GetOldPermitsToCloseAsync(ct);
+ var seen = new HashSet();
+ var closed = 0;
+ foreach (var row in rows)
+ {
+ // the legacy query is a UNION ALL: one permit can appear in several groups and was then closed (and logged) several times
+ if (!seen.Add(row.Id)) continue;
+ var previous = row.Status ?? string.Empty;
+ var done = await uow.ExecuteInTransactionAsync(async token =>
+ {
+ if (await repo.CloseAsync(row.Id, previous, token) == 0) return false; // its status changed since the query
+ await events.LogAsAsync("SYSTEM", null, row.Id, previous, PermitStatus.Closed, PermitEventType.Override, "System Close.", ct: token);
+ return true;
+ }, ct);
+ if (done) closed++;
+ }
+ return closed;
+ }
+}
diff --git a/src/NTP.Application/Jobs/JobCatalog.cs b/src/NTP.Application/Jobs/JobCatalog.cs
new file mode 100644
index 0000000..4f09cf4
--- /dev/null
+++ b/src/NTP.Application/Jobs/JobCatalog.cs
@@ -0,0 +1,47 @@
+using NTP.Application.Grains.Permits;
+
+namespace NTP.Application.Jobs;
+
+///
+/// The jobs the scheduler can run (ports of the legacy jobs\*.cfm files). To add one: add an entry here and make sure its code is safe to
+/// run repeatedly. Everything about WHEN it runs lives in the database (screen "المهام المجدولة", SU only).
+///
+public static class JobCatalog
+{
+ private static T Get(IServiceProvider sp) where T : class => (T)(sp.GetService(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not registered"));
+
+ public static readonly IReadOnlyList All =
+ [
+ new("activate-company-destinations",
+ "تفعيل وجهات الشركات المعلقة", "Activate pending company destinations",
+ "jobs/activateGrainsDestination.cfm: الوجهات التي مضى على تقديمها أكثر من 3 أيام (معلقة) تصبح فعالة، وتلغى الوجهات الفعالة السابقة لنفس القاطرة.",
+ "jobs/activateGrainsDestination.cfm: destinations pending for more than 3 days become active and the truck's previous active destinations are deactivated.",
+ async (sp, ct) =>
+ {
+ var n = await Get(sp).ActivatePendingCompanyDestinationsAsync(ct);
+ return new JobOutcome(n, $"تم تفعيل {n} وجهة");
+ }),
+
+ new("close-old-permits",
+ "إغلاق الارساليات القديمة", "Close old permits",
+ "jobs/GRAINS_Close_Old_Permits.cfm: إغلاق الارساليات التي مضى على تحميلها 48 ساعة، أو التي أكملت التفريغ ولم تغلق، أو المكررة لنفس القاطرة، بحدث \"System Close.\".",
+ "jobs/GRAINS_Close_Old_Permits.cfm: closes permits loaded more than 48 hours ago, finished but not closed, or duplicated for the same truck, with the event \"System Close.\".",
+ async (sp, ct) =>
+ {
+ var n = await Get(sp).CloseOldPermitsAsync(ct);
+ return new JobOutcome(n, $"تم إغلاق {n} إرسالية");
+ }),
+
+ new("fill-company-shares",
+ "استكمال ارساليات الشركات حسب الحصة", "Top up company permits to their share",
+ "jobs/parseGrainsPermits.cfm: لكل شركة، إنشاء إرساليات مفتوحة (على الدور) لتساوي حصتها من الدور في المشول والسائب.",
+ "jobs/parseGrainsPermits.cfm: for every company, creates open permits (on the turn) up to its queue share, for packed and bulk.",
+ async (sp, ct) =>
+ {
+ var n = await Get(sp).FillCompanySharesAsync(ct);
+ return new JobOutcome(n, $"تم إنشاء {n} إرسالية");
+ }),
+ ];
+
+ public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase));
+}
diff --git a/src/NTP.Application/Jobs/JobScheduleRules.cs b/src/NTP.Application/Jobs/JobScheduleRules.cs
new file mode 100644
index 0000000..010467c
--- /dev/null
+++ b/src/NTP.Application/Jobs/JobScheduleRules.cs
@@ -0,0 +1,119 @@
+using System.Globalization;
+
+namespace NTP.Application.Jobs;
+
+/// Pure scheduling rules (no clock, no database), so they can be tested exactly.
+public static class JobScheduleRules
+{
+ public const int MinIntervalMinutes = 1;
+ public const int MaxIntervalMinutes = 7 * 24 * 60;
+ public const int DefaultIntervalMinutes = 60;
+
+ /// A daily time that was missed (application stopped, restart) still runs once if it is at most this late.
+ public static readonly TimeSpan CatchUp = TimeSpan.FromMinutes(30);
+
+ public static bool TryParseTime(string? text, out TimeOnly time) =>
+ TimeOnly.TryParseExact(text?.Trim(), "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out time);
+
+ /// "02:00,13:30" -> times (invalid parts are ignored).
+ public static IReadOnlyList ParseTimes(string? csv)
+ {
+ var list = new List();
+ foreach (var part in (csv ?? string.Empty).Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
+ if (TryParseTime(part, out var t)) list.Add(t);
+ return list.Distinct().OrderBy(t => t).ToList();
+ }
+
+ public static IReadOnlyList SplitTimes(string? csv) => ParseTimes(csv).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)).ToList();
+
+ public static string JoinTimes(IEnumerable? times) =>
+ string.Join(',', (times ?? []).Select(x => TryParseTime(x, out var t) ? t : (TimeOnly?)null).Where(t => t.HasValue)
+ .Select(t => t!.Value).Distinct().OrderBy(t => t).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)));
+
+ /// Returns an Arabic error text, or null when the schedule is valid.
+ public static string? Validate(string? scheduleType, int? intervalMinutes, IReadOnlyList? dailyTimes)
+ {
+ switch (scheduleType)
+ {
+ case JobScheduleTypes.Interval:
+ if (intervalMinutes is null || intervalMinutes < MinIntervalMinutes || intervalMinutes > MaxIntervalMinutes)
+ return "الفترة يجب أن تكون بين دقيقة واحدة و 7 أيام";
+ return null;
+ case JobScheduleTypes.Daily:
+ if (dailyTimes is null || dailyTimes.Count == 0) return "يرجى تحديد وقت واحد على الأقل";
+ if (dailyTimes.Any(x => !TryParseTime(x, out _))) return "صيغة الوقت غير صحيحة، استخدم HH:mm";
+ return null;
+ default:
+ return "نوع الجدولة غير صحيح";
+ }
+ }
+
+ private static DateTime? Latest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a > b ? a : b;
+
+ /// The most recent configured daily time that is not in the future (today or yesterday), if any.
+ private static DateTime? LatestOccurrence(IReadOnlyList times, DateTime now)
+ {
+ DateTime? latest = null;
+ foreach (var day in new[] { -1, 0 })
+ foreach (var t in times)
+ {
+ var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
+ if (occurrence <= now && (latest is null || occurrence > latest)) latest = occurrence;
+ }
+ return latest;
+ }
+
+ /// Is the job due at ? A job that is stopped or still running never is.
+ public static bool IsDue(JobSettingsRow s, DateTime now)
+ {
+ if (!s.IsEnabled || s.IsRunning) return false;
+
+ // a run (or saving / starting the job) closes the window of everything that was due before it
+ var floor = Latest(s.LastStart, s.UpdatedDate);
+
+ if (s.ScheduleType == JobScheduleTypes.Interval)
+ {
+ if (s.IntervalMinutes is not > 0) return false;
+ var anchor = floor ?? now;
+ return now >= anchor.AddMinutes(s.IntervalMinutes.Value);
+ }
+
+ if (s.ScheduleType == JobScheduleTypes.Daily)
+ {
+ var times = ParseTimes(s.DailyTimes);
+ var latest = LatestOccurrence(times, now);
+ if (latest is null || now - latest > CatchUp) return false;
+ return floor is null || latest > floor;
+ }
+ return false;
+ }
+
+ /// When the job runs next (null when it is stopped or has no valid schedule). A job that is due now returns .
+ public static DateTime? NextRun(JobSettingsRow s, DateTime now)
+ {
+ if (!s.IsEnabled) return null;
+ if (IsDue(s, now)) return now;
+
+ if (s.ScheduleType == JobScheduleTypes.Interval)
+ {
+ if (s.IntervalMinutes is not > 0) return null;
+ var anchor = Latest(s.LastStart, s.UpdatedDate) ?? now;
+ var next = anchor.AddMinutes(s.IntervalMinutes.Value);
+ return next < now ? now : next;
+ }
+
+ if (s.ScheduleType == JobScheduleTypes.Daily)
+ {
+ var times = ParseTimes(s.DailyTimes);
+ DateTime? next = null;
+ foreach (var day in new[] { 0, 1 })
+ foreach (var t in times)
+ {
+ var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
+ if (occurrence > now && (next is null || occurrence < next)) next = occurrence;
+ }
+ return next;
+ }
+ return null;
+ }
+}
diff --git a/src/NTP.Application/Jobs/JobService.cs b/src/NTP.Application/Jobs/JobService.cs
new file mode 100644
index 0000000..2bf3df9
--- /dev/null
+++ b/src/NTP.Application/Jobs/JobService.cs
@@ -0,0 +1,107 @@
+using NTP.Application.Abstractions;
+using NTP.Application.Common;
+
+namespace NTP.Application.Jobs;
+
+public interface IJobService
+{
+ Task> ListAsync(CancellationToken ct = default);
+ Task SaveScheduleAsync(string key, SaveJobScheduleRequest request, CancellationToken ct = default);
+ Task StartAsync(string key, CancellationToken ct = default);
+ Task StopAsync(string key, CancellationToken ct = default);
+ Task RunNowAsync(string key, CancellationToken ct = default);
+ Task> RunsAsync(string key, CancellationToken ct = default);
+
+ /// Keys of the jobs that are due now (used by the scheduler loop).
+ Task> GetDueKeysAsync(CancellationToken ct = default);
+}
+
+public sealed class JobService(IJobRepository repo, IJobRunner runner, ICurrentUser user) : IJobService
+{
+ private static JobDefinition Def(string key) =>
+ JobCatalog.Find(key) ?? throw new NotFoundException("Job", key);
+
+ /// The settings of a job that was never saved: stopped, every hour.
+ private static JobSettingsRow Defaults(string key) => new()
+ {
+ JobKey = key, Enabled = 0, ScheduleType = JobScheduleTypes.Interval, IntervalMinutes = JobScheduleRules.DefaultIntervalMinutes
+ };
+
+ private static JobDto ToDto(JobDefinition d, JobSettingsRow s, DateTime now) => new(
+ d.Key, d.TitleAr, d.TitleEn, d.DescriptionAr, d.DescriptionEn,
+ s.IsEnabled, s.ScheduleType ?? JobScheduleTypes.Interval, s.IntervalMinutes ?? JobScheduleRules.DefaultIntervalMinutes,
+ JobScheduleRules.SplitTimes(s.DailyTimes), s.IsRunning, s.LastStart, s.LastEnd, s.LastStatus, s.LastMessage, s.LastCount,
+ JobScheduleRules.NextRun(s, now));
+
+ private async Task<(DateTime Now, Dictionary Rows)> LoadAsync(CancellationToken ct)
+ {
+ var now = await repo.GetServerNowAsync(ct);
+ var rows = (await repo.GetAllAsync(ct)).ToDictionary(r => r.JobKey, StringComparer.OrdinalIgnoreCase);
+ return (now, rows);
+ }
+
+ private async Task OneAsync(string key, CancellationToken ct)
+ {
+ var def = Def(key);
+ var (now, rows) = await LoadAsync(ct);
+ return ToDto(def, rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key), now);
+ }
+
+ public async Task> ListAsync(CancellationToken ct = default)
+ {
+ var (now, rows) = await LoadAsync(ct);
+ return JobCatalog.All.Select(d => ToDto(d, rows.GetValueOrDefault(d.Key) ?? Defaults(d.Key), now)).ToList();
+ }
+
+ public async Task SaveScheduleAsync(string key, SaveJobScheduleRequest r, CancellationToken ct = default)
+ {
+ var def = Def(key);
+ var error = JobScheduleRules.Validate(r.ScheduleType, r.IntervalMinutes, r.DailyTimes);
+ if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
+
+ var daily = r.ScheduleType == JobScheduleTypes.Daily;
+ await repo.SaveScheduleAsync(def.Key, r.ScheduleType, daily ? null : r.IntervalMinutes,
+ daily ? JobScheduleRules.JoinTimes(r.DailyTimes) : null, user.UserId, ct);
+ return await OneAsync(def.Key, ct);
+ }
+
+ public async Task StartAsync(string key, CancellationToken ct = default)
+ {
+ var def = Def(key);
+ var (_, rows) = await LoadAsync(ct);
+ var s = rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key);
+ var error = JobScheduleRules.Validate(s.ScheduleType, s.IntervalMinutes, JobScheduleRules.SplitTimes(s.DailyTimes));
+ if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
+
+ await repo.SetEnabledAsync(def.Key, true, user.UserId, ct);
+ return await OneAsync(def.Key, ct);
+ }
+
+ public async Task StopAsync(string key, CancellationToken ct = default)
+ {
+ var def = Def(key);
+ await repo.SetEnabledAsync(def.Key, false, user.UserId, ct);
+ return await OneAsync(def.Key, ct);
+ }
+
+ public async Task RunNowAsync(string key, CancellationToken ct = default)
+ {
+ var def = Def(key);
+ return await runner.StartAsync(def.Key, user.UserId, ct) == JobStartResult.Started
+ ? new JobActionResult(true, "بدأ تشغيل المهمة")
+ : new JobActionResult(false, "المهمة قيد التنفيذ حاليا");
+ }
+
+ public async Task> RunsAsync(string key, CancellationToken ct = default)
+ {
+ var def = Def(key);
+ return (await repo.GetRunsAsync(def.Key, 30, ct))
+ .Select(r => new JobRunDto(r.Id, r.StartDate, r.EndDate, r.Status, r.RowsAffected, r.Message, r.TriggeredBy)).ToList();
+ }
+
+ public async Task> GetDueKeysAsync(CancellationToken ct = default)
+ {
+ var (now, rows) = await LoadAsync(ct);
+ return JobCatalog.All.Where(d => rows.TryGetValue(d.Key, out var s) && JobScheduleRules.IsDue(s, now)).Select(d => d.Key).ToList();
+ }
+}
diff --git a/src/NTP.Application/Jobs/JobsContracts.cs b/src/NTP.Application/Jobs/JobsContracts.cs
new file mode 100644
index 0000000..2f32287
--- /dev/null
+++ b/src/NTP.Application/Jobs/JobsContracts.cs
@@ -0,0 +1,103 @@
+namespace NTP.Application.Jobs;
+
+/// How a job is scheduled.
+public static class JobScheduleTypes
+{
+ /// Every N minutes (the screen offers minutes or hours), counted from the last start.
+ public const string Interval = "INTERVAL";
+
+ /// At one or more fixed times of the day (HH:mm, server time).
+ public const string Daily = "DAILY";
+}
+
+public static class JobStatuses
+{
+ public const string Running = "RUNNING";
+ public const string Ok = "OK";
+ public const string Failed = "FAILED";
+}
+
+/// What a job reports when it finishes.
+public sealed record JobOutcome(int Count, string? Message = null);
+
+/// One job of the catalog: its key, texts and the code that runs it (called in its own DI scope).
+public sealed record JobDefinition(
+ string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
+ Func> Run);
+
+/// GRAINS_JOBS row (a class: Dapper maps Oracle NUMBER onto properties, not onto positional constructors).
+public sealed class JobSettingsRow
+{
+ public string JobKey { get; set; } = string.Empty;
+ public int? Enabled { get; set; }
+ public string? ScheduleType { get; set; }
+ public int? IntervalMinutes { get; set; }
+ public string? DailyTimes { get; set; }
+ public DateTime? LastStart { get; set; }
+ public DateTime? LastEnd { get; set; }
+ public string? LastStatus { get; set; }
+ public string? LastMessage { get; set; }
+ public int? LastCount { get; set; }
+ public DateTime? UpdatedDate { get; set; }
+ public string? UpdatedBy { get; set; }
+
+ public bool IsEnabled => Enabled == 1;
+ public bool IsRunning => string.Equals(LastStatus, JobStatuses.Running, StringComparison.OrdinalIgnoreCase);
+}
+
+/// GRAINS_JOB_RUNS row.
+public sealed class JobRunRow
+{
+ public long Id { get; set; }
+ public string JobKey { get; set; } = string.Empty;
+ public DateTime StartDate { get; set; }
+ public DateTime? EndDate { get; set; }
+ public string? Status { get; set; }
+ public int? RowsAffected { get; set; }
+ public string? Message { get; set; }
+ public string? TriggeredBy { get; set; }
+}
+
+public sealed record JobDto(
+ string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
+ bool Enabled, string ScheduleType, int IntervalMinutes, IReadOnlyList DailyTimes,
+ bool Running, DateTime? LastStart, DateTime? LastEnd, string? LastStatus, string? LastMessage, int? LastCount, DateTime? NextRun);
+
+public sealed record JobRunDto(long Id, DateTime StartDate, DateTime? EndDate, string? Status, int? RowsAffected, string? Message, string? TriggeredBy);
+
+public sealed record SaveJobScheduleRequest(string ScheduleType, int? IntervalMinutes, IReadOnlyList? DailyTimes);
+
+public sealed record JobActionResult(bool Success, string Message);
+
+public enum JobStartResult { Started, AlreadyRunning }
+
+/// Storage of the job settings and of the run history (tables GRAINS_JOBS / GRAINS_JOB_RUNS, script db/grains-jobs.sql).
+public interface IJobRepository
+{
+ /// Database clock: schedules are judged against it, never against the container clock.
+ Task GetServerNowAsync(CancellationToken ct = default);
+
+ Task> GetAllAsync(CancellationToken ct = default);
+
+ /// Saves the schedule (creates the row when missing, jobs start stopped). Restarts the interval cycle.
+ Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default);
+
+ /// Start (true) / stop (false). Restarts the interval cycle, so a started job never fires for a time that is already past.
+ Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default);
+
+ ///
+ /// Marks the job RUNNING and opens a history row. Returns null when it is already running (a RUNNING mark older than one hour counts as a crash
+ /// and is taken over). The mark lives in the database, so two API instances never run the same job at once.
+ ///
+ Task TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default);
+
+ Task FinishRunAsync(long runId, string key, string status, int? rows, string? message, CancellationToken ct = default);
+
+ Task> GetRunsAsync(string key, int top, CancellationToken ct = default);
+}
+
+/// Starts a job in the background (own DI scope) and records its run. Implemented in Infrastructure.
+public interface IJobRunner
+{
+ Task StartAsync(string key, string triggeredBy, CancellationToken ct = default);
+}
diff --git a/src/NTP.Infrastructure/DependencyInjection.cs b/src/NTP.Infrastructure/DependencyInjection.cs
index 4f09b27..027f257 100644
--- a/src/NTP.Infrastructure/DependencyInjection.cs
+++ b/src/NTP.Infrastructure/DependencyInjection.cs
@@ -3,7 +3,9 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NTP.Application.Abstractions;
using NTP.Application.Common;
+using NTP.Application.Jobs;
using NTP.Infrastructure.HealthChecks;
+using NTP.Infrastructure.Jobs;
using NTP.Infrastructure.Persistence;
namespace NTP.Infrastructure;
@@ -50,6 +52,10 @@ public static class DependencyInjection
services.AddScoped();
services.AddSingleton();
+ // scheduled jobs: the runner starts a job in its own scope, the worker looks for due jobs (screen "المهام المجدولة", SU only)
+ services.AddSingleton();
+ services.AddHostedService();
+
// Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped).
// Do NOT add per-table lines here.
services.AddConventionalServices(typeof(DependencyInjection).Assembly);
diff --git a/src/NTP.Infrastructure/Jobs/JobRunner.cs b/src/NTP.Infrastructure/Jobs/JobRunner.cs
new file mode 100644
index 0000000..e525e22
--- /dev/null
+++ b/src/NTP.Infrastructure/Jobs/JobRunner.cs
@@ -0,0 +1,68 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using NTP.Application.Abstractions;
+using NTP.Application.Common;
+using NTP.Application.Jobs;
+
+namespace NTP.Infrastructure.Jobs;
+
+///
+/// Runs a job of the in the background, in its own DI scope (jobs use scoped services and their own transactions),
+/// and writes the result into GRAINS_JOBS / GRAINS_JOB_RUNS. Used by the scheduler loop ("SCHEDULE") and by the "run now" button (the user id).
+///
+internal sealed class JobRunner(
+ IServiceScopeFactory scopes,
+ ISystemErrorLogger systemErrors,
+ IHostApplicationLifetime lifetime,
+ ILogger logger) : IJobRunner
+{
+ public async Task StartAsync(string key, string triggeredBy, CancellationToken ct = default)
+ {
+ var def = JobCatalog.Find(key) ?? throw new NotFoundException("Job", key);
+
+ long? runId;
+ await using (var scope = scopes.CreateAsyncScope())
+ runId = await scope.ServiceProvider.GetRequiredService().TryBeginRunAsync(def.Key, triggeredBy, ct);
+ if (runId is null) return JobStartResult.AlreadyRunning;
+
+ // the caller (an HTTP request or the scheduler tick) must not wait for the job
+ _ = Task.Run(() => ExecuteAsync(def, runId.Value, triggeredBy), CancellationToken.None);
+ return JobStartResult.Started;
+ }
+
+ private async Task ExecuteAsync(JobDefinition def, long runId, string triggeredBy)
+ {
+ var stopping = lifetime.ApplicationStopping;
+ string status;
+ int? rows = null;
+ string? message;
+ try
+ {
+ await using var scope = scopes.CreateAsyncScope();
+ var outcome = await def.Run(scope.ServiceProvider, stopping);
+ status = JobStatuses.Ok;
+ rows = outcome.Count;
+ message = outcome.Message;
+ logger.LogInformation("Job {Job} finished ({By}): {Message}", def.Key, triggeredBy, message);
+ }
+ catch (Exception ex)
+ {
+ status = JobStatuses.Failed;
+ message = stopping.IsCancellationRequested ? "تم إيقاف التطبيق أثناء التنفيذ" : ex.Message;
+ logger.LogError(ex, "Job {Job} failed ({By})", def.Key, triggeredBy);
+ if (!stopping.IsCancellationRequested)
+ await systemErrors.LogAsync(ex, "SYSTEM", null, null, $"scheduled job {def.Key} ({triggeredBy})");
+ }
+
+ try
+ {
+ await using var scope = scopes.CreateAsyncScope();
+ await scope.ServiceProvider.GetRequiredService().FinishRunAsync(runId, def.Key, status, rows, message, CancellationToken.None);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Could not record the end of job {Job}", def.Key);
+ }
+ }
+}
diff --git a/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs b/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs
new file mode 100644
index 0000000..dc0eea0
--- /dev/null
+++ b/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs
@@ -0,0 +1,72 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using NTP.Application.Common;
+using NTP.Application.Jobs;
+
+namespace NTP.Infrastructure.Jobs;
+
+///
+/// Looks every 20 seconds for jobs that are due (see ) and starts them. What runs and when is set on the
+/// SU screen "المهام المجدولة"; nothing runs until a job is started there. Jobs:SchedulerEnabled=false switches the loop off for
+/// this process (set in appsettings.Development.json so a developer's machine never runs the jobs of a shared database; "run now" still works).
+///
+internal sealed class JobSchedulerWorker(
+ IServiceScopeFactory scopes,
+ IJobRunner runner,
+ IConfiguration configuration,
+ ILogger logger) : BackgroundService
+{
+ private static readonly TimeSpan Tick = TimeSpan.FromSeconds(20);
+ private DateTime _lastTableWarning = DateTime.MinValue;
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ if (configuration.GetValue("Jobs:SchedulerEnabled", true) is false)
+ {
+ logger.LogInformation("Job scheduler is switched off (Jobs:SchedulerEnabled=false)");
+ return;
+ }
+
+ // let the application finish starting first
+ try { await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); } catch (OperationCanceledException) { return; }
+
+ using var timer = new PeriodicTimer(Tick);
+ do
+ {
+ try
+ {
+ IReadOnlyList due;
+ await using (var scope = scopes.CreateAsyncScope())
+ due = await scope.ServiceProvider.GetRequiredService().GetDueKeysAsync(stoppingToken);
+
+ foreach (var key in due)
+ {
+ var result = await runner.StartAsync(key, "SCHEDULE", stoppingToken);
+ logger.LogInformation("Job {Job} is due: {Result}", key, result);
+ }
+ }
+ catch (BusinessException ex) when (ex.Code == "JOBS_TABLE_MISSING")
+ {
+ // the script has not been run on this database: say so now and then, not every 20 seconds
+ if (DateTime.UtcNow - _lastTableWarning > TimeSpan.FromMinutes(30))
+ {
+ _lastTableWarning = DateTime.UtcNow;
+ logger.LogWarning("Scheduled jobs are idle: {Message}", ex.Message);
+ }
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ logger.LogError(ex, "Job scheduler tick failed");
+ }
+ }
+ while (await WaitAsync(timer, stoppingToken));
+ }
+
+ private static async Task WaitAsync(PeriodicTimer timer, CancellationToken ct)
+ {
+ try { return await timer.WaitForNextTickAsync(ct); }
+ catch (OperationCanceledException) { return false; }
+ }
+}
diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs
new file mode 100644
index 0000000..3703e50
--- /dev/null
+++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs
@@ -0,0 +1,62 @@
+using Microsoft.Extensions.Logging;
+using NTP.Application.Grains.Permits;
+
+namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits;
+
+/// SQL of jobs/GRAINS_Close_Old_Permits.cfm.
+internal sealed class PermitJobsRepository(IDbSession session, ILogger logger)
+ : OracleRepositoryBase(session, logger), IPermitJobsRepository
+{
+ // Copied from the legacy query, group by group (the same literals, so the effect is identical):
+ // 1. loaded (LGW) more than 48 hours ago and still on its way (released / accepted / at control / cleared), not for destination 215;
+ // 2. destinations 215 / 220 / 225 whose discharge weighing (DGW) is older than 1600 hours and which are cleared;
+ // 3. a truck with two ACCPT / RESD permits: the older one;
+ // 4. a truck with two REQST / PLND permits (PN above 19999999): the older one.
+ public Task> GetOldPermitsToCloseAsync(CancellationToken ct = default) =>
+ QueryAsync("""
+ select p.id as Id, p.shipmentstatuscode as Status
+ from events e, permits p
+ where e.eventtype = 'LGW'
+ and e.domain = 'GN'
+ and e.permitid = p.id
+ and p.destinationaddressid not in ('215')
+ and p.shipmentstatuscode in ('RESD', 'ACCPT', 'ACTRL', 'CLRPR', 'CLPRL')
+ and sysdate - 48 / 24 > e.eventdate
+ and p.isactive = 'Y'
+ union all
+ select p.id, p.shipmentstatuscode
+ from events e, permits p
+ where e.eventtype = 'DGW'
+ and e.domain = 'GN'
+ and e.permitid = p.id
+ and p.destinationaddressid in ('215', '220', '225')
+ and p.shipmentstatuscode in ('CLRPR', 'CLPRL')
+ and sysdate - 1600 / 24 > e.eventdate
+ and p.isactive = 'Y'
+ union all
+ select p.id, p.shipmentstatuscode
+ from permits p, permits p2
+ where p.shipmentstatuscode in ('ACCPT', 'RESD')
+ and p2.shipmentstatuscode in ('ACCPT', 'RESD')
+ and p.tn = p2.tn
+ and p.domain = 'GN'
+ and p2.domain = 'GN'
+ and p.id < p2.id
+ and p.isactive = 'Y'
+ union all
+ select p.id, p.shipmentstatuscode
+ from permits p, permits p2
+ where p.shipmentstatuscode in ('REQST', 'PLND')
+ and p2.shipmentstatuscode in ('REQST', 'PLND')
+ and p.tn = p2.tn
+ and p.domain = 'GN'
+ and p2.domain = 'GN'
+ and p.id < p2.id
+ and p.pn > 19999999
+ and p.isactive = 'Y'
+ """, null, ct);
+
+ public Task CloseAsync(long permitId, string previousStatus, CancellationToken ct = default) =>
+ ExecuteAsync("UPDATE PERMITS SET shipmentstatuscode = 'CLOSE' WHERE id = :Id AND shipmentstatuscode = :Prev",
+ new { Id = permitId, Prev = previousStatus }, ct);
+}
diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs
new file mode 100644
index 0000000..9b24c42
--- /dev/null
+++ b/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs
@@ -0,0 +1,131 @@
+using System.Data;
+using Dapper;
+using Microsoft.Extensions.Logging;
+using NTP.Application.Common;
+using NTP.Application.Grains.Registry;
+using NTP.Application.Jobs;
+using Oracle.ManagedDataAccess.Client;
+
+namespace NTP.Infrastructure.Persistence.Repositories.Jobs;
+
+/// Tables GRAINS_JOBS and GRAINS_JOB_RUNS of the primary schema (created by db/grains-jobs.sql).
+internal sealed class JobRepository(IDbSession session, ILogger logger)
+ : OracleRepositoryBase(session, logger), IJobRepository
+{
+ private const int MessageBytes = 500;
+
+ /// The scheduler must not crash, and the screen must explain, when the script has not been run yet (ORA-00942).
+ private static async Task Guard(Func> action)
+ {
+ try { return await action(); }
+ catch (OracleException ex) when (ex.Number == 942)
+ {
+ throw new BusinessException("JOBS_TABLE_MISSING", "جداول المهام المجدولة غير موجودة، يرجى تشغيل السكربت db/grains-jobs.sql");
+ }
+ }
+
+ public Task GetServerNowAsync(CancellationToken ct = default) => ExecuteScalarAsync("SELECT SYSDATE FROM DUAL", null, ct);
+
+ public Task> GetAllAsync(CancellationToken ct = default) => Guard(() => QueryAsync("""
+ SELECT j.JOBKEY AS JobKey, j.ENABLED AS Enabled, j.SCHEDULETYPE AS ScheduleType, j.INTERVALMINUTES AS IntervalMinutes,
+ j.DAILYTIMES AS DailyTimes, j.LASTSTARTDATE AS LastStart, j.LASTENDDATE AS LastEnd,
+ -- a RUNNING mark without an open run row (a start that failed) or older than an hour (a crash) is not a running job
+ CASE WHEN j.LASTSTATUS = 'RUNNING'
+ AND (j.LASTSTARTDATE < SYSDATE - 1 / 24
+ OR NOT EXISTS (SELECT 1 FROM GRAINS_JOB_RUNS r WHERE r.JOBKEY = j.JOBKEY AND r.STATUS = 'RUNNING'))
+ THEN NULL ELSE j.LASTSTATUS END AS LastStatus,
+ j.LASTMESSAGE AS LastMessage, j.LASTCOUNT AS LastCount, j.UPDATEDATE AS UpdatedDate, j.UPDATEDBY AS UpdatedBy
+ FROM GRAINS_JOBS j
+ """, null, ct));
+
+ public Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default) =>
+ Guard(async () =>
+ {
+ await ExecuteAsync("""
+ MERGE INTO GRAINS_JOBS j
+ USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
+ WHEN MATCHED THEN UPDATE SET j.SCHEDULETYPE = :Type, j.INTERVALMINUTES = :Interval, j.DAILYTIMES = :Times,
+ j.UPDATEDATE = SYSDATE, j.UPDATEDBY = :UserId
+ WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, DAILYTIMES, UPDATEDATE, UPDATEDBY)
+ VALUES (:Key, 0, :Type, :Interval, :Times, SYSDATE, :UserId)
+ """, new { Key = key, Type = scheduleType, Interval = intervalMinutes, Times = dailyTimes, UserId = userId }, ct);
+ return 0;
+ });
+
+ public Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default) =>
+ Guard(async () =>
+ {
+ await ExecuteAsync("""
+ MERGE INTO GRAINS_JOBS j
+ USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
+ WHEN MATCHED THEN UPDATE SET j.ENABLED = :Enabled, j.UPDATEDATE = SYSDATE, j.UPDATEDBY = :UserId
+ WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, UPDATEDATE, UPDATEDBY)
+ VALUES (:Key, :Enabled, 'INTERVAL', 60, SYSDATE, :UserId)
+ """, new { Key = key, Enabled = enabled ? 1 : 0, UserId = userId }, ct);
+ return 0;
+ });
+
+ public Task TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default) => Guard(async () =>
+ {
+ // make sure the row exists (a job that was never configured can still be run by hand)
+ await ExecuteAsync("""
+ MERGE INTO GRAINS_JOBS j
+ USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
+ WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, UPDATEDATE, UPDATEDBY)
+ VALUES (:Key, 0, 'INTERVAL', 60, SYSDATE, :UserId)
+ """, new { Key = key, UserId = triggeredBy }, ct);
+
+ // The guarded update is the lock: only one caller (in any API instance) can flip the row to RUNNING. A RUNNING mark is also taken
+ // over when no run row is open any more (a start that failed half way) or when it is older than an hour (a crash).
+ var taken = await ExecuteAsync("""
+ UPDATE GRAINS_JOBS
+ SET LASTSTATUS = 'RUNNING', LASTSTARTDATE = SYSDATE, LASTENDDATE = NULL, LASTMESSAGE = NULL, LASTCOUNT = NULL
+ WHERE JOBKEY = :Key
+ AND (LASTSTATUS IS NULL OR LASTSTATUS <> 'RUNNING' OR LASTSTARTDATE < SYSDATE - 1 / 24
+ OR NOT EXISTS (SELECT 1 FROM GRAINS_JOB_RUNS r WHERE r.JOBKEY = :Key AND r.STATUS = 'RUNNING'))
+ """, new { Key = key }, ct);
+ if (taken == 0) return null;
+
+ try
+ {
+ // bind names must not be Oracle reserved words (BY, ROWS ... give ORA-01745)
+ var p = new DynamicParameters(new { Key = key, RunBy = triggeredBy });
+ p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
+ await ExecuteAsync("""
+ INSERT INTO GRAINS_JOB_RUNS (ID, JOBKEY, STARTDATE, STATUS, TRIGGEREDBY)
+ VALUES (SEQ_GRAINS_JOB_RUNS.NEXTVAL, :Key, SYSDATE, 'RUNNING', :RunBy)
+ RETURNING ID INTO :NewId
+ """, p, ct);
+ return OracleSql.ToInt64(p.Get