Jovemnf.Schedule
1.0.2
dotnet add package Jovemnf.Schedule --version 1.0.2
NuGet\Install-Package Jovemnf.Schedule -Version 1.0.2
<PackageReference Include="Jovemnf.Schedule" Version="1.0.2" />
<PackageVersion Include="Jovemnf.Schedule" Version="1.0.2" />
<PackageReference Include="Jovemnf.Schedule" />
paket add Jovemnf.Schedule --version 1.0.2
#r "nuget: Jovemnf.Schedule, 1.0.2"
#:package Jovemnf.Schedule@1.0.2
#addin nuget:?package=Jovemnf.Schedule&version=1.0.2
#tool nuget:?package=Jovemnf.Schedule&version=1.0.2
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 | Versions 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. |
-
net9.0
- Cronos (>= 0.8.4)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
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.