Jovemnf.Schedule 1.0.2

dotnet add package Jovemnf.Schedule --version 1.0.2
                    
NuGet\Install-Package Jovemnf.Schedule -Version 1.0.2
                    
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" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jovemnf.Schedule" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Jovemnf.Schedule" />
                    
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 --version 1.0.2
                    
#r "nuget: Jovemnf.Schedule, 1.0.2"
                    
#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@1.0.2
                    
#: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&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Jovemnf.Schedule&version=1.0.2
                    
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 (1)

Showing the top 1 NuGet packages that depend on Jovemnf.Schedule:

Package Downloads
Jovemnf.Schedule.MySql

MySQL storage implementation for Jovemnf.Schedule.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 152 2/19/2026
1.0.1 123 2/18/2026
1.0.0 124 2/18/2026