CronScheduler.AspNetCore
注意:预释放软件包是通过feedz.io分发的。
概括
您是否厌倦了复杂的调度库使您无法构建可扩展和高效的应用程序?别再看!引入Cronscheduler ,这是专门为.NET Core IHost或IWebHost设计的轻便且易于使用的库。
Cronscheduler是基于亲吻原则的,是石英调度程序及其替代方案的简化替代方案。使用Cronscheduler,您可以轻松地使用CRON语法安排任务,并在任何.NET Core Generichost IHost中进行操作,从而使设置和配置变得轻而易举。
但这不是全部!我们还介绍了Istartupjob ,可以在主机准备启动之前对关键过程的异步初始化。这意味着您即使在复杂的kubernetes环境中,您的应用程序也可以正确初始化并顺利运行。
好处:
- 轻巧且易于使用的库
- 用cron语法简化调度
- 在.NET Core Generichost
IHost或IWebHost中运行 - 与ISTARTUPJOB对关键过程的异步初始化支持
立即加入Cronscheduler社区,并开始简化应用程序的调度需求!
请参阅迁移指南以进行升级。
给星星!
如果您愿意或正在使用此项目学习或启动解决方案,请给它一颗星。谢谢!
安装
- 安装
AspNetCore托管.NET CLI的软件包
dotnet add package CronScheduler.AspNetCore
- 为
IHost托管.NET CLI安装软件包
dotnet add package CronScheduler.Extensions
使用crontab格式进行工作/任务时间表
该图书馆最多支持Crontab格式的5秒钟工作间隔,感谢Hangfireio/Cronos库。
您可以使用https://cront*ab*-*generator.org/来生成所需的工作/任务时间表。
cron格式
cron表达是定义固定时间,日期和间隔的掩码。面具包括第二(可选),分钟,小时,每月和每天的每日田野。所有字段都允许您指定多个值,如果所有字段都包含匹配值,则任何给定的日期/时间都将满足指定的CRON表达式。
Allowed values Allowed special characters Comment
┌───────────── second (optional) 0-59 * , - /
│ ┌───────────── minute 0-59 * , - /
│ │ ┌───────────── hour 0-23 * , - /
│ │ │ ┌───────────── day of month 1-31 * , - / L W ?
│ │ │ │ ┌───────────── month 1-12 or JAN-DEC * , - /
│ │ │ │ │ ┌───────────── day of week 0-6 or SUN-SAT * , - / # L ? Both 0 and 7 means SUN
│ │ │ │ │ │
* * * * * *
演示应用
- cronschedulerworker-此示例演示了如何使用新的Microsoft .NET核心工人模板使用
CronScheduler - cronschedulerapp-此示例演示了如何将
CronScheduler与Aspnetcore应用程序使用。
可以在调度程序作业中注册选项和作业有两种方法。
- 基本和最有效的注册方法是通过
IConfiguration
此作业注册假设作业名称的名称是相同的。
services . AddScheduler ( ctx => { ctx . AddJob < TestJob > ( ) ; } ) ;
- 相同Cron工作的复杂工厂注册,具有不同的选择
services . AddScheduler ( ctx => { var jobName1 = \"TestJob1\" ; ctx . AddJob ( sp => { var options = sp . GetRequiredService < IOptionsMonitor < SchedulerOptions > > ( ) . Get ( jobName1 ) ; return new TestJobDup ( options , mockLoggerTestJob . Object ) ; } , options => { options . CronSchedule = \"*/5 * * * * *\" ; options . RunImmediately = true ; } , jobName : jobName1 ) ; var jobName2 = \"TestJob2\" ; ctx . AddJob ( sp => { var options = sp . GetRequiredService < IOptionsMonitor < SchedulerOptions > > ( ) . Get ( jobName2 ) ; return new TestJobDup ( options , mockLoggerTestJob . Object ) ; } , options => { options . CronSchedule = \"*/5 * * * * *\" ; options . RunImmediately = true ; } , jobName : jobName2 ) ; } ) ;
Singleton计划工作及其依赖项的示例代码
public class TorahQuoteJob : IScheduledJob { private readonly TorahQuoteJobOptions _options ; private readonly TorahVerses _torahVerses ; private readonly TorahService _service ; /// <summary> /// Initializes a new instance of the <see cref=\"TorahQuoteJob\"/> class. /// </summary> /// <param name=\"options\"></param> /// <param name=\"service\"></param> /// <param name=\"torahVerses\"></param> public TorahQuoteJob ( IOptionsMonitor < TorahQuoteJobOptions > options , TorahService service , TorahVerses torahVerses ) { _options = options . Get ( Name ) ; _service = service ?? throw new ArgumentNullException ( nameof ( service ) ) ; _torahVerses = torahVerses ?? throw new ArgumentNullException ( nameof ( torahVerses ) ) ; } // job name and options name must match. public string Name { get ; } = nameof ( TorahQuoteJob ) ; public async Task ExecuteAsync ( CancellationToken cancellationToken ) { var index = new Random ( ) . Next ( _options . Verses . Length ) ; var exp = _options . Verses [ index ] ; _torahVerses . Current = await _service . GetVersesAsync ( exp , cancellationToken ) ; } }
然后在Program.cs中注册此服务。CS:
var builder = WebApplication . CreateBuilder ( args ) ; // Add services to the container. builder . Services . AddScheduler ( builder => { builder . Services . AddSingleton < TorahVerses > ( ) ; builder . Services . AddHttpClient < TorahService > ( ) . AddTransientHttpErrorPolicy ( p => p . RetryAsync ( ) ) ; builder . AddJob < TorahQuoteJob , TorahQuoteJobOptions > ( ) ; builder . Services . AddScoped < UserService > ( ) ; builder . AddJob < UserJob , UserJobOptions > ( ) ; builder . AddUnobservedTaskExceptionHandler ( sp => { var logger = sp . GetRequiredService < ILoggerFactory > ( ) . CreateLogger ( \"CronJobs\" ) ; return ( sender , args ) => { logger ? . LogError ( args . Exception ? . Message ) ; args . SetObserved ( ) ; } ; } ) ; } ) ; builder . Services . AddBackgroundQueuedService ( applicationOnStopWaitForTasksToComplete : true ) ; builder . Services . AddDatabaseDeveloperPageExceptionFilter ( ) ; builder . Services . AddStartupJob < SeedDatabaseStartupJob > ( ) ; builder . Services . AddStartupJob < TestStartupJob > ( ) ; builder . Logging . AddConsole ( ) ; builder . Logging . AddDebug ( ) ; builder . Logging . AddConfiguration ( builder . Configuration . GetSection ( \"Logging\" ) ) ; var app = builder . Build ( ) ; // Configure the HTTP request pipeline. if ( app . Environment . IsDevelopment ( ) ) { app . UseDeveloperExceptionPage ( ) ; app . UseMigrationsEndPoint ( ) ; } else { app . UseExceptionHandler ( \"/Home/Error\" ) ; app . UseHsts ( ) ; } app . UseHttpsRedirection ( ) ; app . UseStaticFiles ( ) ; app . UseCookiePolicy ( ) ; app . UseAuthentication ( ) ; app . UseRouting ( ) ; app . MapControllers ( ) ; app . MapDefaultControllerRoute ( ) ; app . MapRazorPages ( ) ; await app . RunStartupJobsAsync ( ) ; await app . RunAsync ( ) ;
在申请IStartupJobs之前
有许多情况下,用于使用IWebHost接口或IGenericHost启动Jobs。最常见的情况是确保创建和更新数据库。该库通过简单地进行以下操作使其成为可能:
- 在
Program.cs文件中添加以下内容:
var builder = WebApplication . CreateBuilder ( args ) ; // Add services to the container. builder . Services . AddStartupJob < SeedDatabaseStartupJob > ( ) ; builder . Services . AddStartupJob < TestStartupJob > ( ) ; var app = builder . Build ( ) ; // Configure the HTTP request pipeline. await app . RunStartupJobsAsync ( ) ; await app . RunAsync ( ) ;
背景队列
在应用程序的某些情况下,需要排队任务。为了Startup.cs此添加以下内容。
services . AddBackgroundQueuedService ( ) ;
然后添加示例异步任务以由排队的托管服务执行。
public class MyService { private readonly IBackgroundTaskQueue _taskQueue ; public MyService ( IBackgroundTaskQueue taskQueue ) { _taskQueue = taskQueue ; } public void RunTask ( ) { _taskQueue . QueueBackgroundWorkItem ( async ( token ) => { // run some task await Task . Delay ( TimeSpan . FromSeconds ( 10 ) , token ) ; } } ) ; } }
执照
麻省理工学院许可证
