linkdotnet / linkdotnet/BlogExamples

Cron - Not running multiple instances of a job

Offen
#2 2 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Vorherrschende Sprache
C#
Sterne
124
Forks
24
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

This is not an elaborate solution, but it works (in theory). You can't choose to have multiple instances running or not. I just assumed not to have multiple instances running regardless. I assumed this is not required unless you are running a job every minute or two.

I added a field to the scheduler that tracks the Task returned by job.Run(stoppingToken);. On ever tick check the list for completed tasks and clear them. Prior to running a job skip if it is on the list of running jobs.

I'm sure this might need some tweaking this was my first attempt at it.

private Dictionary<string, Task> _runningJobs;

.
.
.

// Clear completed jobs
foreach (var key in _runningJobs.Keys)
{
    if (_runningJobs[key].IsCompleted)
    {
        _runningJobs[key].Dispose();
        _runningJobs.Remove(key);
    }
}

// Run jobs that are in the map
RunActiveJobs(runMap, now, stoppingToken);

.
.
.

foreach (var run in currentRuns)
{

    // We are sure (thanks to our extension method)
    // that the service is of type ICronJob
    var job = (ICronJob)_serviceProvider.GetRequiredService(run);
    string jobName = job.GetType().Name;

    // Continue to next job if job is already running
    if (_runningJobs.ContainsKey(jobName))
    {
        continue;
    }

    // We don't want to await jobs explicitly because that
    // could interfere with other job runs
    var task = job.Run(stoppingToken);

    // Add task to running jobs
    _runningJobs.Add(jobName, task);
}

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, die Verarbeitung des Scheduler-Ticks, den Einstiegspunkt ICronJob und die Aufrufe von job.Run(stoppingToken) zu finden. Verfolge, wie geplante Jobs ausgewählt und nachverfolgt werden. Die Aufgabe ist abgeschlossen, wenn ein geplanter Job nicht erneut gestartet wird, solange seine vorherige Task noch läuft, während spätere Ausführungen nach Abschluss gestartet werden können.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
csharp
Bereich
backend
Issue-Typ
Feature
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.