網(wǎng)站首頁 編程語言 正文
前言
前段時間需要在一個新項目里添加兩個后臺任務,去定時請求兩個供應商的API來同步數(shù)據(jù);由于項目本身只是一個很小的服務,不太希望引入太重的框架,同時也沒持久化要求;于是我開始尋找在Quartz.Net、Hangfire之外,是否還有更為輕量級的框架滿足我的要求,最終我選擇了Coravel.
簡介
Coravel是一個專為.NET Core設計的.NET Standard庫,除了任務調(diào)度,還提供了像隊列、緩存、郵件等其它高級功能。特點就是對開發(fā)者十分友好,接入十分簡單、優(yōu)雅、流暢,接近于零配置。
作為一個生于2018年的年輕項目,后發(fā)優(yōu)勢明顯,一開始就是基于.Net Standard 2.0實現(xiàn),沒有歷史負擔,同時又可以利用很多.Net Core新特性。
用法
首先安裝Coravel包
dotnet add package coravel
下面演示在.Net 6 Minimal API項目中接入Coravel并設置兩個定時任務,是不是非常簡單:)
using Coravel; var builder = WebApplication.CreateBuilder(args); //只使用Coravel的任務調(diào)度功能 builder.Services.AddScheduler(); //注冊你自己的調(diào)度任務 builder.Services.AddTransient<YourCoravelJob1>(); builder.Services.AddTransient<YourCoravelJob2>(); var app = builder.Build(); //配置任務 app.Services.UseScheduler(scheduler => { scheduler.Schedule<YourCoravelJob1>().EveryFiveMinutes(); //每5分鐘執(zhí)行一次Job1 scheduler.Schedule<YourCoravelJob2>().Hourly().Monday(); // 每周一每小時執(zhí)行一次 });
Coravel預先定義好了很多常用的間隔頻率,非常的全面,像上面用到的?EveryFiveMinutes()
?和?Hourly()
,是不是非常的簡單優(yōu)雅;當然Coravel也支持Cron表達式。
Invocable
?是Coravel中的核心概念,代表一個獨立的任務,上面的YourCoravelJob1和YourCoravelJob2就是?Invocable
,Coravel直接調(diào)度這些Invocable
。
要創(chuàng)建你自己的Invocable
,只需實現(xiàn)?IInvocable
接口,在?Invoke
方法中編碼你的任務。
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來實現(xiàn)后臺定時任務。(因此只有.Net Core 2.0以上的項目才能使用Coravel)
public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); }
SchedulerHost即實現(xiàn)了IHostedService接口,在 其StartAsync
方法中,當程序完全啟動時,注冊了一個的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
?激活到點的Invocable
,同時會根據(jù)情況將任務分組,在單獨的線程分開執(zhí)行。從這里可以看到Coravel是支持秒級任務的。
在?StopAsync
?方法中,會先等待正在執(zhí)行的任務完成才會關閉,這個功能還是比較重要。
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é)
本文介紹一個對開發(fā)者友好的、輕量級、零配置的.Net Standard庫Coravel,并演示了如何使用Coravel在.Net 6 Minimal API中創(chuàng)建定時任務,最后淺析了的實現(xiàn)原理。作為一個年輕的框架,Coravel站在了巨人的肩膀上,相比Quartz.Net、Hangfire,也擁有很多亮點特性,很值得嘗試。
到此這篇關于.Net Core使用Coravel實現(xiàn)任務調(diào)度的文章就介紹到這了,更多相關.Net Core Coravel實現(xiàn)任務調(diào)度內(nèi)容請搜索AB教程網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持AB教程網(wǎng)!
參考鏈接
- https://github.com/jamesmh/coravel
- https://docs.coravel.net
- https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host
原文鏈接:https://www.cnblogs.com/netry/p/coravel-for-task-scheduling.html
相關推薦
- 2024-03-03 layui彈窗編輯表單清空
- 2023-04-03 c++?lambda捕獲this?導致多線程下類釋放后還在使用的錯誤問題_C 語言
- 2023-03-17 Docker部署Nginx并修改配置文件的兩種方式_docker
- 2022-06-15 Python實現(xiàn)RSA加密解密_python
- 2022-09-18 Go語言包管理工具Godep的用法_Golang
- 2022-12-06 Python基礎面向?qū)ο笾^承與派生詳解_python
- 2022-05-25 文字解說Golang?Goroutine和線程的區(qū)別_Golang
- 2022-11-06 Django中Migrate和Makemigrations實操詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支