Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Cron - Not running multiple instances of a job #2

Copy link
Copy link
@y2k4life

Description

@y2k4life
Issue body actions

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);
}
Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.