Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Apr 11

Coravel - Easy task scheduling for your .NET web apps

Coravel - Easy task scheduling for your .NET web apps
Автор:
Источник:
Просмотров:
3417

Sometimes you need to run scheduled tasks for your .NET web app.

Automated report creation, status checks, routine admin tasks, that sort of thing.

I spent the last few weeks migrating Practical ASP.NET to .NET 8 (static SSR).

One requirement involved sending data to an external service.

For this I decided to keep things simple and rely on a crude mechanism to create records in a database table, then periodically check that table for records in order to send them on to the external service (via its API).

Historically, for this kind of task, I would have turned to Quartz.net, or possibly Hangfire.

But as I started to work on the requirement I remembered Coravel.

Coravel for easy task scheduling

Coravel is new to me, but from the GitHub repo looks to have been around for about 6 years or so (at the time of writing).

The docs are well worth a look as Coravel can handle a number of ’tricky’ tasks for your web app, including:

  • Task Scheduling
  • Queuing
  • Caching
  • Event Broadcasting
  • Mailing

For my specific case, I wanted to run a scheduled task on a regular basis to check the DB table and call the external API.

To make this work with Coravel requires an Invocable

public class SendEventsToThirdParty(AppDbContext dbContext, ThirdPartyApi thirdPartyApi) : IInvocable
{
    public async Task Invoke()
    {
        var events = dbContext.SyncEvents.Take(20).ToArray();
        await thirdPartApi.SendEvents(events);
        dbContext.SyncEvents.RemoveRange(events);
        await dbContext.SaveChangesAsync();
    }    
}

This is a straightforward C# class which implements IInvocable.

IInvocable requires us to implement the Invoke method.

As with any task scheduling it’s important to ensure your business logic is atomic and can stand being run multiple times, potentially in quick succession.

In this case grabbing 20 records from the DB and syncing them in one API call is ‘good enough’ for my requirements.

To actually schedule the task there are two steps.

First, we need to register the invocable as a service.

Program.cs

builder.Services.AddTransient<SendEventsToThirdParty>();

Then schedule it:

Program.cs

app.Services.UseScheduler(scheduler =>
{
    scheduler.Schedule<SendEventsToThirdParty>()
        .EverySeconds(30);
});

The fluent API has plenty of options for scheduling the task.

Coravel

Or you can use CRON if you prefer.

scheduler.Schedule<SendEventsToThirdParty>()
    .Cron()

With that, the task is scheduled, and will run every 30 seconds (so long as the web app is running).

In memory scheduling made easy

It’s worth noting this doesn’t persist the scheduled tasks anywhere, so there’s no mechanism to retry a ‘missed’ scheduled task if your app is down for a period of time.

In this case, with atomic operations being run every 30 seconds that isn’t an issue.

But if you do need task persistence/retries you can check out older, well established options such as Hangfire.

Otherwise, Coravel is a convenient, easy to use option.

A swiss army knife for your web app

Finally, Coravel has similarly straightforward APIs for other common background tasks, like caching, raising events, sending emails.

For example, in the same app, I need to use a third party service to generate a checkout link when someone goes to purchase a course/ebook.

Once a checkout link has been generated it can be used for every subsequent attempt to purchase a product.

So it makes sense to cache the generated link, and re-use it (at least for a period of time).

Here’s how I used Coravel to cache the checkout link, using an in-memory cache.

private async Task Buy()
{
    var checkout = await Cache.RememberAsync("SomeUniqueKey", CreateCheckout, TimeSpan.FromMinutes(60));
        
    NavMan.NavigateTo(checkout.data.attributes.url);
}

private async Task CreateCheckout()
{
    // business logic to call third party API
}

The first attempt to assign a value to checkout will invoke the CreateCheckout method (because there’s nothing in the cache).

The result will be cached, so the next attempt will retrieve the cached entry (until the cache expires, after 60 minutes).

In summary

Coravel makes it quick and easy to tackle scheduled tasks, and other common modern web app requirements.

You can create invocables for your key business logic, then schedule them using its scheduler, and use its simple APIs for other common tasks, like sending emails, handling events and caching data.

Похожее
Jan 11, 2023
Author: Nitesh Singhal
Database Setup with DbUp + Postgresql + Dapper in ASP.Net Core In this tutorial, we are going to explore how we can setup our database on startup when using Dapper for accessing database. When using Dapper, one of the key...
Dec 25, 2023
Author: Binod Mahto
Testing coverage is the key part of any project development and Testing coverage is not only about the unit testing instead Integration Testing is extremely important to make sure entire system is unbroken & bug free with any change or...
Dec 21, 2023
Author: Jeremy Wells
Introduction and prerequisites This post is part of an ongoing series where we build a “walking skeleton” application using ASP.NET Core and Angular as well as other technologies for deployment and testing. By now, our application is a minimally functional...
Apr 26
Author: HarrySrangal
You can’t miss these 50 questions if you are preparing for interviews. Last month I was preparing for the interviews and I have collated all the questions from different companies. Although there were many questions but I have picked top...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Выгорание эволюционирует. Что такое «тихий уход» — новый тренд среди офисных сотрудников
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Модуль, пакет, библиотека, фреймворк: разбираемся в разнице
Что должен уметь Frontend разработчик в 2023 году (+Roadmap)
«Чистые» и «нечистые» функции в JavaScript
Как мы столкнулись с версионированием и осознали, что вариант «просто проставить цифры» не работает
NULL в SQL: что это такое и почему его знание необходимо каждому разработчику
О кодировках и кодовых страницах
Семь итераций наивности или как я полтора года свою дебютную игру писал
Зачем нужен MediatR?
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile