.Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟
目錄
- 前言
- 簡(jiǎn)介
- 用法
- 原理
- 總結(jié)
- 參考鏈接
前言
前段時(shí)間需要在一個(gè)新項(xiàng)目里添加兩個(gè)后臺(tái)任務(wù),去定時(shí)請(qǐng)求兩個(gè)供應(yīng)商的API來同步數(shù)據(jù);由于項(xiàng)目本身只是一個(gè)很小的服務(wù),不太希望引入太重的框架,同時(shí)也沒持久化要求;于是我開始尋找在Quartz.Net、Hangfire之外,是否還有更為輕量級(jí)的框架滿足我的要求,最終我選擇了Coravel.
簡(jiǎn)介
Coravel是一個(gè)專為.NET Core設(shè)計(jì)的.NET Standard庫,除了任務(wù)調(diào)度,還提供了像隊(duì)列、緩存、郵件等其它高級(jí)功能。特點(diǎn)就是對(duì)開發(fā)者十分友好,接入十分簡(jiǎn)單、優(yōu)雅、流暢,接近于零配置。
作為一個(gè)生于2018年的年輕項(xiàng)目,后發(fā)優(yōu)勢(shì)明顯,一開始就是基于.Net Standard 2.0實(shí)現(xiàn),沒有歷史負(fù)擔(dān),同時(shí)又可以利用很多.Net Core新特性。
用法
首先安裝Coravel包
dotnet add package coravel
下面演示在.Net 6 Minimal API項(xiàng)目中接入Coravel并設(shè)置兩個(gè)定時(shí)任務(wù),是不是非常簡(jiǎn)單:)
using Coravel; var builder = WebApplication.CreateBuilder(args); //只使用Coravel的任務(wù)調(diào)度功能 builder.Services.AddScheduler(); //注冊(cè)你自己的調(diào)度任務(wù) builder.Services.AddTransient<YourCoravelJob1>(); builder.Services.AddTransient<YourCoravelJob2>(); var app = builder.Build(); //配置任務(wù) app.Services.UseScheduler(scheduler => { scheduler.Schedule<YourCoravelJob1>().EveryFiveMinutes(); //每5分鐘執(zhí)行一次Job1 scheduler.Schedule<YourCoravelJob2>().Hourly().Monday(); // 每周一每小時(shí)執(zhí)行一次 });
Coravel預(yù)先定義好了很多常用的間隔頻率,非常的全面,像上面用到的 EveryFiveMinutes()
和 Hourly()
,是不是非常的簡(jiǎn)單優(yōu)雅;當(dāng)然Coravel也支持Cron表達(dá)式。
Invocable
是Coravel中的核心概念,代表一個(gè)獨(dú)立的任務(wù),上面的YourCoravelJob1和YourCoravelJob2就是 Invocable
,Coravel直接調(diào)度這些Invocable
。
要?jiǎng)?chuàng)建你自己的Invocable
,只需實(shí)現(xiàn) IInvocable
接口,在 Invoke
方法中編碼你的任務(wù)。
public class YourCoravelJob1 : IInvocable { private readonly ILogger _logger; public YourCoravelJob1(ILogger<YourCoravelJob1> logger) { _logger = logger; } public async Task Invoke() { _logger.LogInformation("start.."); } } }
原理
Coravel使用是的.Net Core 2.0引入的IHostedService來實(shí)現(xiàn)后臺(tái)定時(shí)任務(wù)。(因此只有.Net Core 2.0以上的項(xiàng)目才能使用Coravel)
public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); }
SchedulerHost即實(shí)現(xiàn)了IHostedService接口,在 其StartAsync
方法中,當(dāng)程序完全啟動(dòng)時(shí),注冊(cè)了一個(gè)的Timer
public Task StartAsync(CancellationToken cancellationToken) { this._lifetime.ApplicationStarted.Register(InitializeAfterAppStarted); return Task.CompletedTask; } private void InitializeAfterAppStarted() { this._timer = new Timer(this.RunSchedulerPerSecondAsync, null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } private async void RunSchedulerPerSecondAsync(object state) { if (this._schedulerEnabled) { await this._scheduler.RunSchedulerAsync(); } }
每秒調(diào)用 RunSchedulerAsync
激活到點(diǎn)的Invocable
,同時(shí)會(huì)根據(jù)情況將任務(wù)分組,在單獨(dú)的線程分開執(zhí)行。從這里可以看到Coravel是支持秒級(jí)任務(wù)的。
在 StopAsync
方法中,會(huì)先等待正在執(zhí)行的任務(wù)完成才會(huì)關(guān)閉,這個(gè)功能還是比較重要。
public async Task StopAsync(CancellationToken cancellationToken) { this._schedulerEnabled = false; // Prevents changing the timer from firing scheduled tasks. this._timer?.Change(Timeout.Infinite, 0); this._scheduler.CancelAllCancellableTasks(); // If a previous scheduler execution is still running (due to some long-running scheduled task[s]) // we don"t want to shutdown while they are still running. if (this._scheduler.IsRunning) { this._logger.LogWarning(ScheduledTasksRunningMessage); } while (this._scheduler.IsRunning) { await Task.Delay(50); } }
總結(jié)
本文介紹一個(gè)對(duì)開發(fā)者友好的、輕量級(jí)、零配置的.Net Standard庫Coravel,并演示了如何使用Coravel在.Net 6 Minimal API中創(chuàng)建定時(shí)任務(wù),最后淺析了的實(shí)現(xiàn)原理。作為一個(gè)年輕的框架,Coravel站在了巨人的肩膀上,相比Quartz.Net、Hangfire,也擁有很多亮點(diǎn)特性,很值得嘗試。
到此這篇關(guān)于.Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的文章就介紹到這了,更多相關(guān).Net Core Coravel實(shí)現(xiàn)任務(wù)調(diào)度內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
參考鏈接
- https://github.com/jamesmh/coravel
- https://docs.coravel.net
- https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host
