linkdotnet / linkdotnet/BlogExamples

Cron - Not running multiple instances of a job

Open
#2 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
124
Forks
24
PR merge metrics
No merged PRs in 30d

Description

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 _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);
}
```

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the scheduler tick handling, the ICronJob entry point, and the calls to job.Run(stoppingToken). Trace how scheduled jobs are selected and tracked. Done means a scheduled job is not started again while its previous task is still running, while later runs can start after completion.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.