Friday, March 15, 2024

Schedular Services using Coravel in .net core

Simple example of how to schedule job using Coravel in .net core
Coravel gives you a zero-configuration queue that runs in-memory. This is useful to offload long-winded tasks to the background instead of making your users wait for their HTTP request to finish.

Step 1 : Create a console app named CorvelJob

Step 2 : Install Coravel, Microsoft.Extension.DependencyInjection & Microsoft.Extension.Hosting

Step 3 : Below code written in Program.cs will run in every 2 seconds

using Coravel;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = Host.CreateApplicationBuilder();

builder.Services.AddScheduler();

var app = builder.Build();

app.Services.UseScheduler(schedular =>
{
    schedular.ScheduleAsync(
        async () =>
        {
            await Task.Delay(20);
            Console.WriteLine("Schiedular Time : " + DateTime.Now);
        }).EverySeconds(2);


});
app.Run();

OutPut : 

Schiedular Time : 3/15/2024 3:02:40 PM
Schiedular Time : 3/15/2024 3:02:42 PM
Schiedular Time : 3/15/2024 3:02:44 PM

You can also configure above code that run only on weekend that to on Sunday

schedular.ScheduleAsync(
        async () =>
        {
            await Task.Delay(20);
            Console.WriteLine("Schiedular Time : " + DateTime.Now);
        }).Weekly().Weekend().Sunday().Once();

 

you can invoke you class file also. Let take an example of MailerTask which sends mail only on weekend

Create MailerTask.cs

using Coravel;
using CorvelJob;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = Host.CreateApplicationBuilder();

builder.Services.AddScheduler();
builder.Services.AddTransient<MailerTask>();
var app = builder.Build();
app.Services.UseScheduler(schedular =>
{
    schedular.Schedule<MailerTask>()
        .Weekly().Weekend().Sunday()
        .PreventOverlapping("identifier");


});
app.Run();

 

Output : 

info: CorvelJob.MailerTask[0]

   Mail sent @ 03/15/2024 15:13:20

info: CorvelJob.MailerTask[0]

   Mail sent @ 03/15/2024 15:15:20