

GitHub - jamesmh/coravel: .Net Core meets Laravel: Scheduling, Queuing, etc.
source link: https://github.com/jamesmh/coravel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md
Coravel
Inspired by all the awesome features that are baked into the Laravel PHP framework - coravel seeks to provide additional features that .Net Core lacks like:
- Task Scheduling
- Queuing
- Mailer [TBA]
- Command line tools integrated with coraval features [TBA]
- More???
Features
Quick-Start
Add the nuget package Coravel
to your .NET Core app. Done!
1. Scheduling Tasks
Tired of using cron and Windows Task Scheduler? Want to use something easy that ties into your existing code?
In Startup.cs
, put this in ConfigureServices()
:
services.AddScheduler(scheduler => { scheduler.Schedule( () => Console.WriteLine("Run at 1pm utc during week days.") ) .DailyAt(13, 00); .Weekday(); } );
Easy enough? Look at the documentation to see what methods are available!
2. Task Queuing
Tired of having to install and configure other systems to get a queuing system up-and-running? Tired of using databases to issue queued tasks? Look no further!
In Startup.cs
, put this in ConfigureServices()
:
services.AddQueue();
Voila! Too hard?
To append to the queue, inject IQueue
into your controller (or wherever injection occurs):
using Coravel.Queuing.Interfaces; // Don't forget this! // Now inside your MVC Controller... IQueue _queue; public HomeController(IQueue queue) { this._queue = queue; }
And then call:
this._queue.QueueTask(() => Console.WriteLine("This was queued!") );
Now you have a fully functional queue!
Task Scheduling
Usually, you have to configure a cron job or a task via Windows Task Scheduler to get a single or multiple re-occuring tasks to run. With coravel you can setup all your scheduled tasks in one place! And it's super easy to use!
Initial Setup
In your .NET Core app's Startup.cs
file, inside the ConfigureServices()
method, add the following:
services.AddScheduler(scheduler => { scheduler.Schedule( () => Console.WriteLine("Every minute during the week.") ) .EveryMinute(); .Weekday(); } );
This will run the task (which prints to the console) every minute and only on weekdays (not Sat or Sun). Simple enough?
How Does It Work?
The AddScheduler()
method will configure a new Hosted Service that will run in the background while your app is running.
A Scheduler
is provided to you for configuring what tasks you want to schedule. It has a method Schedule()
which accepts a System.Action
. This contains the logic / code of the task you want to run.
After calling Schedule()
you can chain method calls further to specify:
- The interval of when your task should be run (once a minute? every hour? etc.)
- Specific times when you want your task to run
- Restricting which days your task is allowed to run on (Monday's only? etc.)
Example: Run a task once an hour only on Mondays.
scheduler.Schedule( () => Console.WriteLine("Hourly on Mondays.") ) .Hourly() .Monday();
Example: Run a task every day at 1pm
scheduler.Schedule( () => Console.WriteLine("Daily at 1 pm.") ) .DailyAtHour(13); // Or .DailyAt(13, 00)
Error Handling
Any tasks that throw errors will just be skipped and the next task in line will be invoked.
If you want to catch errors and do something specific with them you may use the OnError()
method.
services.AddScheduler(scheduler => // Assign your schedules ) .OnError((exception) => doSomethingWithException(exception) );
You can, of course, add error handling inside your specific tasks too.
Scheduling Tasks
After you have called the Schedule()
method on the Scheduler
, you can begin to configure the schedule constraints of your task.
Intervals
First, methods to apply interval constraints are available.
Basic Intervals
These methods tell your task to execute at basic intervals.
Using any of these methods will cause the task to be executed immedately after your app has started. Then they will only be executed again once the specific interval has been reached.
If you restart your app these methods will cause all tasks to run again on start. To avoid this, use an interval method with time constraints (see below).
EveryMinute();
EveryFiveMinutes();
EveryTenMinutes();
EveryFifteenMinutes();
EveryThirtyMinutes();
Hourly();
Daily();
Weekly();
Intervals With Time Contraints
These methods allow you specify an interval and a time constraint so that your scheduling is more specific and consistent.
Please note that the scheduler is using UTC time. So, for example, using DailyAt(13, 00)
will run your task daily at 1pm UTC time.
HourlyAt(int minute)
DailyAtHour(int hour)
DailyAt(int hour, int minute)
Day Constraints
After specifying an interval, you can further chain to restrict what day(s) the scheduled task is allowed to run on.
All these methods are further chainable - like Monday().Wednesday()
. This would mean only running the task on Mondays and Wednesdays. Be careful since you could do something like this .Weekend().Weekday()
which basically means there are no constraints (it runs on any day).
Monday()
Tuesday()
Wednesday()
Thursday()
Friday()
Saturday()
Sunday()
Weekday()
Weekend()
Feature: Task Queuing
Coravel allows zero-configuration queues (at run time). The queue hooks into the scheduling mechanism (although that is handled for you).
The scheduler checks for scheduled tasks every minute. If there are any available items in the queue, then it will invoke them all.
Setup
In your Startup
file, in the ConfigureServices()
just do this:
services.AddQueue();
That's it! This will automatically register the queue in your service container.
How To Queue Tasks
In your controller that is using DI, inject a Coravel.Queuing.Interfaces.IQueue
.
You use the QueueTask()
method to add a task to the queue.
IQueue _queue; public HomeController(IQueue queue) { this._queue = queue; } //... Further down ... public IActionResult QueueTask() { // Call .QueueTask() to add item to the queue! this._queue.QueueTask(() => Console.WriteLine("This was queued!")); return Ok(); }
Handling Errors
Since the queue is hooked into the scheduling mechanism, the OnError()
extension method that corvel provides will be used for your queued tasks.
Again, you may use proper error handling in your tasks too.
On App Closing
When your app is stopped, coravel will attempt to gracefully wait until the last moment and:
- Run the scheduler once last time
- Consume any tasks remaining in the queue
You shouldn't have to worry about loosing any queued items.
If your server was shutdown in a non-graceful way etc. (unplugged... etc.) then you may lose active queued tasks. But under normal circumstances, even when forcefully shutting down your app, coravel will (in the background) handle this for you.
Recommend
-
7
There’s a tried-and-true architecture that I’ve seen many times for supporting your web services and applications: PostgreSQL for data storage Redis for coordinating background job queues (and some limited atomic operati...
-
5
Distributing speaking time can be tricky when meeting face to face, but it is usuallly worse in virtual meetings. Especially those spanning long distances. In my current team, I learned how queues in remote meetings can make them b...
-
47
An Ultimate Guide to Message Queuing Telemetry Transport (MQTT) Message Queuing Telemetry Transport (MQTT) is a lightweight open messaging protocol. IoT trends provide resource-constrained network clients with a simple...
-
5
Video: Understanding Queuing Theory and Software Performance What do McDonald’s drive-thru lines, highway on-ramp metering lights, and stadium beer service all have in common with software? They’re a...
-
8
MongoMQ2 MongoMQ2 is a light-weight Node.js library that turns MongoDB collections into general-purpose message queues or event logs, without additional server components. At a slight expense of throughput com...
-
8
<?xml encoding="utf-8" ??>Introduction Message queuing is a micro-service architecture that allows you to move data between different applications for further processing. In this model, end-user...
-
3
Modern web development often includes traffic-heavy web applications and APIs. These services are tasked with a double-whammy: they need to…Modern web development often includes traffic-heavy web applications and APIs. These services...
-
5
Enabling Seamless Kafka Async Queuing with Consumer Proxy Skip to footer ...
-
22
.Net Core使用Coravel实现任务调度 ...
-
7
事件溯源CQRS不必引入最终一致性 - jamesmh 解道Jdon
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK