linkdotnet / linkdotnet/BlogExamples

Cron - Not running multiple instances of a job

未關閉
#2 2 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
C#
星號
124
分支
24
PR 合併指標
30 天內沒有已合併 PR

描述

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

貢獻指南

這個儲存庫沒有索引到貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

首先定位 scheduler tick 的處理邏輯、ICronJob 進入點以及對 job.Run(stoppingToken) 的呼叫。追蹤排程工作如何被選取和追蹤。完成標準是:排程工作在其上一次 task 仍在執行時不會再次啟動,但在完成後可以啟動後續執行。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
csharp
領域
backend
Issue 類型
功能
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。