Jovemnf.Schedule.MySql 1.0.3

dotnet add package Jovemnf.Schedule.MySql --version 1.0.3
                    
NuGet\Install-Package Jovemnf.Schedule.MySql -Version 1.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Jovemnf.Schedule.MySql" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jovemnf.Schedule.MySql" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Jovemnf.Schedule.MySql" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Jovemnf.Schedule.MySql --version 1.0.3
                    
#r "nuget: Jovemnf.Schedule.MySql, 1.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Jovemnf.Schedule.MySql@1.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Jovemnf.Schedule.MySql&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=Jovemnf.Schedule.MySql&version=1.0.3
                    
Install as a Cake Tool

Jovemnf.Schedule

Agendador de tarefas leve, persistente e distribuível para .NET, focado em simplicidade e performance com armazenamento em MySQL.

✨ Principais Características

  • API Fluente: Agende jobs com facilidade usando a interface IScheduler.
  • Persistência em MySQL: Jobs e execuções armazenados de forma robusta.
  • Múltiplos Triggers: Suporte para Intervalos (Simple Interval), Cron e execuções únicas (Once).
  • Concorrência Controlada: Defina o limite de execuções simultâneas por Job.
  • Resiliência: Recuperação automática de jobs interrompidos e políticas de Misfire (RunOnce, Skip, CatchUp).

🛠️ Instalação e Configuração

No seu Program.cs, registre o agendador e adicione seus handlers:

builder.Services.AddSchedule(options => {
    options.PollIntervalMs = 15000; // Intervalo de busca de novos jobs
})
.AddMySqlStore("Server=localhost;Database=sched;Uid=root;Pwd=...")
.AddJobHandler<EmailJob>();

Inicialização do Banco

Execute a inicialização durante o bootstrap da aplicação:

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var store = scope.ServiceProvider.GetRequiredService<IJobStore>();
    await store.InitAsync();
}

app.Run();

📝 Como Criar um Job

Implemente IJobHandler e decore a classe com [JobHandler].

[JobHandler("notificacoes.email")]
public class EmailJob : IJobHandler
{
    public async Task ExecuteAsync(JobContext context, CancellationToken ct)
    {
        var data = context.GetPayload<EmailRequest>();
        Console.WriteLine($"Enviando email para: {data.To}");
        await Task.CompletedTask;
    }
}

🚀 Agendando Jobs (Injeção de Dependência)

Qualquer classe gerenciada pelo .NET (Services, Controllers, Workers) pode receber o IScheduler no construtor.

1. Crie seu Serviço
// Exemplo de um serviço de negócio
public class PedidoService(IScheduler scheduler)
{
    public async Task CriarPedido(int id)
    {
        // Agendamento Único (Imediato)
        await scheduler.ScheduleAsync<EmailJob>(new { OrderId = id });
    }
}
2. Registre-o no DI (Program.cs)
builder.Services.AddSchedule(...)
       .AddMySqlStore(...);

// Registre seu serviço para que o .NET possa injetar o scheduler nele
builder.Services.AddScoped<PedidoService>();
3. Use em um Controller ou API
[ApiController]
[Route("pedidos")]
public class PedidosController(PedidoService pedidoService) : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Post(int id)
    {
        await pedidoService.CriarPedido(id);
        return Ok();
    }
}

📅 Estratégias de Agendamento (IScheduler)

Utilize os métodos fluídos da interface IScheduler para diferentes cenários:

// No seu serviço...
public async Task Exemplos(int id)
{
        // Execução Única (Imediata)
        await scheduler.ScheduleAsync<EmailJob>(new { OrderId = id });

        // Execução com Atraso (Delay) - Ex: Daqui a 30 minutos
        await scheduler.ScheduleAsync<EmailJob>(TimeSpan.FromMinutes(30), new { OrderId = id });

        // Execução em Data Específica
        await scheduler.ScheduleAsync<EmailJob>(DateTimeOffset.UtcNow.AddDays(7), new { Promo = "BlackFriday" });

        // Execução com Intervalo (Repetição)
        await scheduler.ScheduleIntervalAsync<EmailJob>(TimeSpan.FromMinutes(10), new { OrderId = id });

        // Execução com Cron
        await scheduler.ScheduleCronAsync<EmailJob>("0 0 * * *", new { Report = "daily" });
    }
}

🧪 Exemplos de Teste (Unit Testing)

A biblioteca foi desenhada para ser testável. Você pode usar mocks para IScheduler em seus testes unitários.

public class PedidoServiceTests
{
    [Fact]
    public async Task DeveAgendarEmailAoCriarPedido()
    {
        // Arrange
        var schedulerMock = new Mock<IScheduler>();
        var service = new PedidoService(schedulerMock.Object);

        // Act
        await service.CriarPedido(123);

        // Assert
        schedulerMock.Verify(s => s.ScheduleAsync(
            It.Is<JobCreate>(j => j.Handler == "EmailJob"), 
            It.IsAny<CancellationToken>()
        ), Times.Once);
    }
}

Desenvolvido por Jovemnf. Licença MIT.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.3 129 3/13/2026
1.0.2 120 2/19/2026
1.0.1 121 2/18/2026
1.0.0 114 2/18/2026